해결
코드
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
58
59
60
61
62
63
64
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Main {
static int[] dr = {0,-1,0,1};
static int[] dc = {-1,0,1,0};
static int[][] input, room;
static int N;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
input = new int[N+1][N+1];
room = new int[N+1][N+1];
for(int i = 1; i < N+1; i++) {
String[] str = br.readLine().split("");
for(int j = 1; j < N+1; j++) {
input[i][j] = Integer.parseInt(str[j-1]);
room[i][j] = Integer.MAX_VALUE;
}
}
BFS(1,1);
System.out.println(room[N][N]);
}
static void BFS(int x, int y) {
Queue<Node> q = new LinkedList<>();
q.add(new Node(x,y));
room[x][y] = 0;
while (!q.isEmpty()){
Node temp = q.poll();
int r = temp.r;
int c = temp.c;
for(int i =0; i < 4; i++){
int nr = r + dr[i];
int nc = c + dc[i];
if(nr < 1 || nr > N || nc < 1 || nc > N) continue; //범위 확인
if(room[nr][nc] <= room[r][c]) continue; //방문 확인 및 갱신 조건 확인
q.add(new Node(nr,nc));
if(input[nr][nc] == 1 ) room[nr][nc] = room[r][c]; // 벽이 아니면 벽 숫자는 그대로
else {
room[nr][nc] = room[r][c]+1; //벽이면 +1
}
}
}
}
}
class Node{
int r;
int c;
public Node(int r, int c) {
this.r = r;
this.c = c;
}
}
참고
- 직접구현