-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14940.cpp
79 lines (70 loc) · 1.51 KB
/
14940.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
70
71
72
73
74
75
76
77
78
79
#include<iostream>
#include<queue>
using namespace std;
const int bucketsize = 1e3;
int n,m;
int map[bucketsize][bucketsize];
int dist[bucketsize][bucketsize];
pair<int,int> start;
void input() {
cin>>n>>m;
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
cin>>map[i][j];
if(map[i][j]==2) {
start = {i,j};
map[i][j]=0;
}
}
}
}
bool check_range(int x,int y) {
return x>=0 && x<n && y>=0 && y<m;
}
void solution() {
queue<pair<int,int>> q;
q.push(start);
while(!q.empty()) {
int fx = q.front().first;
int fy = q.front().second;
q.pop();
for(int i=0; i<4; i++) {
int nx = fx + "2011"[i] - '1';
int ny = fy + "1120"[i] - '1';
if(!check_range(nx,ny)) {
continue;
}
if(!map[nx][ny]) {
continue;
}
if(dist[nx][ny]) {
continue;
}
dist[nx][ny] = dist[fx][fy] + 1;
q.push({nx,ny});
}
}
}
void print() {
for(int i=0; i<n; i++) {
for(int j=0; j<m; j++) {
if(map[i][j]==1 && !dist[i][j]) {
cout<<-1<<' ';
} else {
cout<<dist[i][j]<<' ';
}
}
cout<<'\n';
}
}
void solve() {
input();
solution();
print();
}
int main() {
cin.tie(NULL);
cout.tie(NULL);
ios_base::sync_with_stdio(false);
solve();
}