공부기록/백준

[백준] 미로탐색

메델 2023. 11. 6. 10:11
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {

    static int[][] map;
    static int N, M;
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        N = kb.nextInt();
        M = kb.nextInt();
        map = new int[N][M];

        for (int i = 0; i < N; i++) {
            String a = kb.next();
            for (int j = 0; j < M; j++) {
                map[i][j] = a.charAt(j) - '0';
            }
        }

        int result = bfs(0, 0);
        System.out.println(result);
    }

    public static int bfs(int x, int y) {
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[] {x, y});

        while (!queue.isEmpty()) {
            int[] now = queue.poll();
            int cX = now[0];
            int cY = now[1];

            for (int i = 0; i < 4; i++) {
                int nextX = cX + dx[i];
                int nextY = cY + dy[i];

                if (nextX >= 0 && nextX < N && nextY >= 0 && nextY < M && map[nextX][nextY] == 1) {
                    map[nextX][nextY] = map[cX][cY] + 1;
                    queue.offer(new int[] {nextX, nextY});
                }
            }
        }

        return map[N - 1][M - 1];
    }
}

'공부기록 > 백준' 카테고리의 다른 글

[백준] 11047번 동전 0  (0) 2023.11.10
[백준] 2018번 수들의 합 5  (0) 2023.11.08
[백준] 2941번 크로아티아 알파벳  (0) 2023.10.15
[백준] 9012번 괄호  (0) 2023.10.15
[백준] 10773번 제로  (0) 2023.10.15