자두의 데브로그

[자바] 프로그래머스 게임 맵 최단거리 본문

코딩테스트/문제 풀이

[자바] 프로그래머스 게임 맵 최단거리

왕자두 2024. 8. 24. 21:58

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

 

프로그래머스

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

programmers.co.kr

 

미로 게임이랑 거의 유사하지만 만약 가는 길이 없으면 가장 마지막에 -1로 출력해야되는 부분이 달랐다. 최단 거리를 구하는 문제이기 때문에 bfs를 구현해서 풀면 됐었는데, bfs의 for문 내에서 queue에 값을 추가해야하는 것을 까먹고 재귀로 넣어서 첫 번째 풀이는 틀렸었다. 탐색을 시작하는 지점은 (0, 0) 좌표이기 때문에 애초에 bfs(0, 0)을 실행하면 된다. visited[0][0]은 bfs 함수를 처음 실행하기 전에 true로 만들어주고 bfs 내부에서 방문할 때 true로 바꿔주면 된다.

 

import java.util.*;

class Solution {
    static int[][] graph;
    static boolean[][] visited;
    static int[] dx = {0, 0, 1, -1};
    static int[] dy = {1, -1, 0, 0};
    
    public int solution(int[][] maps) {
        graph = maps;
        visited = new boolean[maps.length][maps[0].length];
        visited[0][0] = true;
        bfs(0, 0);
        int answer = -1;
        if(graph[maps.length - 1][maps[0].length - 1] != 1){
            answer = graph[maps.length - 1][maps[0].length - 1];
        }
        return answer;
    }
    
    public static void bfs(int x, int y){
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{x, y});
        
        while(!queue.isEmpty()){
            int[] now = queue.poll();
            int now_x = now[0];
            int now_y = now[1];
            visited[now_x][now_y] = true;
            
            for(int i = 0; i < 4; i++){
                int next_x = now_x + dx[i];
                int next_y = now_y + dy[i];
                if(next_x < graph.length && next_y < graph[0].length && next_x >= 0 && next_y >= 0){
                    if(graph[next_x][next_y] == 1 && !visited[next_x][next_y]){
                        queue.add(new int[]{next_x, next_y});
                        visited[next_x][next_y] = true;
                        graph[next_x][next_y] = graph[now_x][now_y] + 1;
                    }
                
                }
            }
        }
    }
}