[백준 | Java] 2178 미로 탐색

알린·2024년 2월 13일

baekjoon

목록 보기
29/68

내 풀이

문제의 제목 그대로 미로 탐색이기 때문에 0,0에서 n, m까지의 최단거리를 구하면 되므로 각 정점마다의 최단거리를 구할 수 있는 BFS로 풀이했다.

풀이과정은 다음과 같다.

  1. 미로를 입력받을 때 띄어쓰기 없이 입력 받기
  2. 상하좌우를 탐색해 갈수있는 위치를 큐에 삽입,방문 표시, 거리 삽입
  3. 큐가 빌 때 까지 다시 상하좌우 탐색 반복
  4. N, M 번째 칸에 삽입된 숫자 출력

위의 1번 예제 수행 시 다음과 같이 배열이 채워지며, N, M 칸에 있는 15가 답이 된다.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {
    static int N;
    static int M;
    static int[][] miro;
    static boolean[][] visited;
    static int[] dx = {0, 0, 1, -1};  // x방향 배열 (좌우)
    static int[] dy = {1, -1, 0, 0};  // y방향 배열 (상하)
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        miro = new int[N+1][M+1];
        visited = new boolean[N+1][M+1];

        for (int i = 0; i < N; i++) {
            String tmp = br.readLine();
            for (int j = 0; j < M; j++) {
                miro[i][j] = tmp.charAt(j)-'0';
            }
        }
        bfs(0);
        System.out.println(miro[N-1][M-1]);
    }

    static void bfs(int start) {
        Queue<int[]> queue = new LinkedList<>();

        queue.add(new int[]{start, start});
        visited[start][start] = true;

        while (!queue.isEmpty()) {
            // 큐에서 해당 위치 꺼내기
            int xy[] = queue.poll();
            // 해당 위치에서 상하좌우로 이동
            for (int i = 0; i < 4; i++) {
                int nx = xy[0] + dx[i];
                int ny = xy[1] + dy[i];

                // 이동한 위치가 미로의 범위를 벗어나거나, 이미 방문한 위치이거나, 값이 0일 때
                if (nx < 0 || ny < 0 || nx > N || ny > M || visited[nx][ny] || miro[nx][ny] == 0)
                    continue;
                else {
                    queue.add(new int[]{nx, ny});
                    visited[nx][ny] = true;
                    miro[nx][ny] = miro[xy[0]][xy[1]]+1;  // 이동한 위치의 값에 현재 위치까지의 거리 +1 대입
                }
            }
        }
    }
}

profile
짱이 되고싶은 개발 기록

0개의 댓글