-
Notifications
You must be signed in to change notification settings - Fork 0
/
2206.cpp
69 lines (51 loc) · 1.13 KB
/
2206.cpp
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
#include<iostream>
#include<queue>
#include<tuple>
using namespace std;
char board[1001][1001];
int visit[1001][1001][2];
int dx[4] = { 0, 1, 0, -1 };
int dy[4] = { 1,0,-1,0 };
int r, c;
int bfs() {
queue<tuple<int, int, int>> q;
q.push({ 0,0,0 });
visit[0][0][0] = visit[0][0][1] = 1;
while (!q.empty())
{
int x, y, wall;
tie(x, y, wall) = q.front(); q.pop();
if (x == c - 1 && y == r - 1) {
return visit[x][y][wall];
}
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= c || ny < 0 || ny >= r) {
continue;
}
if (board[nx][ny] == '0' && visit[nx][ny][wall] == -1) {
q.push({ nx,ny,wall });
visit[nx][ny][wall] = visit[x][y][wall] + 1;
}
if (!(wall) && board[nx][ny] == '1' && visit[nx][ny][1] == -1) {
q.push({ nx,ny,1 });
visit[nx][ny][1] = visit[x][y][0] + 1;
}
}
}
return -1;
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> c >> r;
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
cin >> board[i][j];
visit[i][j][0] = visit[i][j][1] = -1;
}
}
int result = bfs();
cout << result << endl;
}