Algorithm/JAVA - BOJ

BOJ/백준 - 2178 미로 탐색 JAVA

ㅇㅇ잉 2021. 8. 18. 23:53

배열로 입력받고,

BFS로 탐색한다.

처음엔 어라,,어떻게 카운트하지? 싶었는데

그냥 방문하면서 배열에 더해가면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
 
public class Main {
    static int N,M;
    static int result = 0;
    static int[][] arr;
    static boolean[][] visit;
    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());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
 
        arr = new int[N][M];
        visit = new boolean[N][M];
 
        for(int i=0;i<N;i++){
            String str = br.readLine();
            for(int j=0;j<M;j++){
                arr[i][j]= str.charAt(j)-'0';
            }
        }
        bfs();
        System.out.print(arr[N-1][M-1]);
    }
 
    static void bfs(){
        Queue<Point> q = new LinkedList<>();
        q.offer(new Point(0,0));
        result++;
 
        while(!q.isEmpty()){
            Point cur = q.poll();
            visit[cur.x][cur.y]=true;
 
            for(int i=0;i<4;i++){
                int nxtx = cur.x+dx[i];
                int nxty = cur.y+dy[i];
                //범위 밖이면
                if(nxtx<0 || nxty<0 || nxtx>=|| nxty>=M) continue;
                if(arr[nxtx][nxty]==1 && !visit[nxtx][nxty]){
                    q.offer(new Point(nxtx,nxty));
                    arr[nxtx][nxty]=arr[cur.x][cur.y]+1;
                    visit[nxtx][nxty]=true;
                }
            }
        }
    }
}
cs