Scroll indicator done
728x90

https://www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

www.acmicpc.net

 

 

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

// 이동할 때마다 이동 횟수를 (전 칸 + 1) 해주는 것
// 그래야 같은 거리로 이동한 칸들을 같게 처리할 수 있다
public class Main {
    static int[] dx = {0, 0, -1, 1};
    static int[] dy = {1, -1, 0, 0};
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        int[][] arr = new int[n][m];
        for (int i = 0; i < n; i++) {
            String[] strArray = br.readLine().split("");
            for (int j = 0; j < m; j++) {
                arr[i][j] = Integer.parseInt(strArray[j]);
            }
        }

        boolean[][] visited = new boolean[n][m];
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[]{0, 0});
        while (!queue.isEmpty()) {
            int[] point = queue.poll();
            int x = point[0];
            int y = point[1];

            for (int i = 0; i < 4; i++) {
                int nx = x + dx[i];
                int ny = y + dy[i];

                if(nx < 0 || ny < 0 || nx >= n || ny >= m) continue;
                if (arr[nx][ny] == 1 && !visited[nx][ny]) {
                    arr[nx][ny] = arr[x][y] + 1;
                    queue.add(new int[]{nx, ny});
                    visited[nx][ny] = true;
                }
            }
        }
        
        System.out.println(arr[n-1][m-1]);
    }
}

728x90

'BAEKJOON > Java' 카테고리의 다른 글

[B7576][토마토][java]  (0) 2023.10.08
[B2667][단지번호붙이기][java]  (0) 2023.10.08
[B1260][DFS와 BFS][java]  (0) 2023.10.08
[B2606][바이러스][java]  (0) 2023.10.08
[B2156][포도주 시식][java]  (0) 2023.10.08