-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2206.java
86 lines (74 loc) · 2.41 KB
/
2206.java
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
public class Main {
static int[][] dir = {
{0, 1},
{0, -1},
{1, 0},
{-1, 0}
};
static int[][] map;
static int N, M;
static class Pos {
int y;
int x;
int cnt;
boolean crushed;
Pos(int y, int x, int cnt, boolean crushed) {
this.y = y;
this.x = x;
this.cnt = cnt;
this.crushed = crushed;
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
N = Integer.parseInt(input[0]);
M = Integer.parseInt(input[1]);
map = new int[N][M];
for(int i = 0; i < N; i++) {
input = br.readLine().split("");
for(int j = 0; j < M; j++) {
map[i][j] = Integer.parseInt(input[j]);
}
}
search();
}
public static void search() {
boolean[][][] visited = new boolean[N][M][2];
Queue<Pos> queue = new LinkedList<>();
queue.add(new Pos(0, 0, 1, false));
while(!queue.isEmpty()) {
Pos pos = queue.poll();
if(pos.y == N - 1 && pos.x == M - 1) {
System.out.println(pos.cnt);
return;
}
for(int i = 0; i < 4; i++) {
int ny = pos.y + dir[i][0];
int nx = pos.x + dir[i][1];
if(ny < 0 || ny >= N || nx < 0 || nx >= M) continue;
if(map[ny][nx] == 1) {
if(pos.crushed) continue;
queue.add(new Pos(ny, nx, pos.cnt + 1, true));
visited[ny][nx][1] = true;
}
else {
if(pos.crushed && !visited[ny][nx][1]) {
queue.add(new Pos(ny, nx, pos.cnt + 1, true));
visited[ny][nx][1] = true;
}
else if(!pos.crushed && !visited[ny][nx][0]) {
queue.add(new Pos(ny, nx, pos.cnt + 1, false));
visited[ny][nx][0] = true;
}
}
}
}
System.out.println(-1);
}
}