기록하는 개발자

[백준][JAVA] 2178 : 미로 탐색 본문

Algorithm

[백준][JAVA] 2178 : 미로 탐색

밍맹030 2021. 8. 14. 21:40
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.StringTokenizer;
import java.util.Queue;
import java.util.LinkedList;

public class Main {
    static int[][] miro;
    static boolean[][] checked;
    static int n, m;
    static int[] dx = { -1, 1, 0, 0 };
    static int[] dy = { 0, 0, -1, 1 };

    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][m];
        checked = new boolean[n][m];
        checked[0][0] = true;

        for(int i=0; i<n; i++) {
            String s = br.readLine();
            for(int j=0; j<m; j++)
                miro[i][j] = s.charAt(j)-'0';
        }

        bfs(0, 0);
        System.out.println(miro[n-1][m-1]);
    }

    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 nowX = now[0], nowY = now[1];

            for(int i=0; i<4; i++) { // 현 위치에서 상하좌우 갈 수 있는지 검사
                int nextX = nowX + dx[i], nextY = nowY + dy[i];

                if (nextX>=n || nextY>=m || nextX<0 || nextY<0) continue;
                if (miro[nextX][nextY]==0 || checked[nextX][nextY]) continue;

                queue.add(new int[] {nextX, nextY});
                miro[nextX][nextY] = miro[nowX][nowY]+1; // 다음 갈 칸 = 현위치+1
                checked[nextX][nextY] = true;
            }
        }
    }
}
728x90

'Algorithm' 카테고리의 다른 글

[백준][JAVA] 9935 : 문자열 폭발  (0) 2021.09.11
[백준][JAVA] 2230 : 수 고르기  (0) 2021.08.24
[백준][JAVA] 2579: 계단 오르기  (0) 2021.08.14
[백준][JAVA] 14501 : 퇴사  (0) 2021.08.14
[백준][JAVA] 10989: 수 정렬하기3  (0) 2021.08.09