주녘공부일지

[프로그래머스 C#] Lv.3 미로 탈출 명령어 본문

CodingTest/Programmers Lv.3

[프로그래머스 C#] Lv.3 미로 탈출 명령어

주녘 2024. 10. 11. 17:49

https://school.programmers.co.kr/learn/courses/30/lessons/150365

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

주어진 크기의 격자 미로에서 주어진 조건에 따라 출발지에서 목적지로 가는 명령어를 구하는 문제

- 이동 우선순위 : d -> l -> r -> u  //  x축이 위아래임을 주의

- 한번 이동했던 위치로 다시 이동할 수 있음

- 출발지에서 도착지로 딱 맞게 도착해야 함

즉, 목적지에 딱 맞게 도착할 수 있다면 우선순위에 따른 이동을 먼저 수행해야 함

 

풀이 코드

using System;
using System.Text;

public class Solution
{
    public enum EDirType { d = 0, l = 1, r = 2, u = 3 }
    public int GetMinDis(int x, int y, int r, int c) => Math.Abs(x - r) + Math.Abs(y - c);
    
    public string solution(int n, int m, int x, int y, int r, int c, int k)
    {
        // 도착할 수 없음
        if(GetMinDis(x, y, r, c) > k || (GetMinDis(x, y, r, c) % 2 != 0 && k % 2 == 0))
            return "impossible";

        StringBuilder sb = new StringBuilder();
        
        int[] dirY = new int[4] { 0, -1, 1, 0 };
        int[] dirX = new int[4] { 1, 0, 0, -1 };
                
        // 최단거리가 될 때까지 우선순위 이동
        while(k != GetMinDis(x, y, r, c))
        {
            k--;
            for(int i = 0; i < 4; i++)
            {
                int moveX = x + dirX[i];
                int moveY = y + dirY[i];
                
                if(1 <= moveX && moveX <= n && 1 <= moveY && moveY <= m)
                {
                    x = moveX;
                    y = moveY;
                    sb.Append(((EDirType)i).ToString());
                    break;
                }
            }
        }
        
        // 최단거리 이동 d l r u
        while(x < r) { sb.Append('d'); x++; }
        while(y > c) { sb.Append('l'); y--; }
        while(y < c) { sb.Append('r'); y++; }
        while(x > r) { sb.Append('u'); x--; }
        
        return sb.ToString();
    }
}