[프로그래머스][Java] 게입 맵 최단거리 (Lv.2) - DFS/BFS

박현아·2024년 11월 7일
0

programmers-java

목록 보기
30/35

👩‍💻 문제

🙋‍♀️ 답변

import java.util.LinkedList;
import java.util.Queue;

class Solution {
    public int solution(int[][] maps) {
        
        int n = maps.length;
        int m = maps[0].length;
        
        // 상하좌우 방향 (상,하,좌,우)
        int[] dx = {-1, 1, 0, 0};
        int[] dy = {0, 0, -1, 1};
        
        // BFS 큐
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0});
        
        // 시작 지점 거리 초기화
        maps[0][0] = 1;
        
        while (!queue.isEmpty()) { // 큐가 비어있지 않으면
            int[] current = queue.poll();
            int x = current[0];
            int y = current[1];
            
            // 목표 지점에 도달했을 경우
            if (x == n-1 && y == m-1) {
                return maps[x][y];
            }
            
            // 상하좌우로 이동
            for (int i=0; i<4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];
                
                // 맵 안에 있고, 벽이 아닌 곳
                if (nx >= 0 && nx < n && ny >= 0 && ny < m && maps[nx][ny] == 1) {
                    maps[nx][ny] = maps[x][y] +1; // 거리 기록
                    queue.offer(new int[]{nx, ny});
                }
            }
        }
        
        // 목표 지점에 도달할 수 없는 경우
        return -1;
    }
}

🤔

0개의 댓글