-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path14940_최단거리.cpp
74 lines (62 loc) · 1.28 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
#include <math.h>
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
int n, m;
int board[1001][1001] = {
0,
};
int result[1001][1001] = {
0,
};
int visited[1001][1001] = {
0,
};
queue<pair<int, int> > pq;
void bfs() {
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
while (!pq.empty()) {
int x = pq.front().first;
int y = pq.front().second;
pq.pop();
for (int i = 0; i < 4; i++) {
int nextX = x + dx[i];
int nextY = y + dy[i];
if (nextX < 0 || nextX >= n || nextY < 0 || nextY >= m) {
continue;
}
if (board[nextX][nextY] == 1 && !visited[nextX][nextY]) {
visited[nextX][nextY] = 1;
result[nextX][nextY] = result[x][y] + 1;
pq.push(make_pair(nextX, nextY));
}
}
}
}
int main() {
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> board[i][j];
if (board[i][j] == 2) {
pq.push(make_pair(i, j));
}
}
}
bfs();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (result[i][j] == 0 && board[i][j] == 1) {
cout << -1 << " ";
} else {
cout << result[i][j] << " ";
}
}
cout << "\n";
}
return 0;
}