-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path쉬운 최단거리.cc
102 lines (92 loc) · 2.44 KB
/
쉬운 최단거리.cc
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
using namespace std;
int n, m;
int x, y;
vector<vector<int>> map;
vector<vector<int>> result;
vector<vector<bool>> visited;
int bfs() {
queue<pair<int,int>> q;
visited.assign(n,vector<bool>(m,false));
q.push(make_pair(x,y));
visited[x][y] = true;
result[x][y] = 0;
int cnt = 0;
while (!q.empty())
{
pair<int,int> k = q.front();
q.pop();
int i = k.first;
int j = k.second;
if (map[i][j] == 0) {
result[i][j] = 0;
}
else {
if (i-1 >= 0) {
if (!visited[i-1][j]) {
q.push(make_pair(i-1,j));
visited[i-1][j] = true;
result[i-1][j] = result[i][j] + 1;
}
}
if (i+1 < n) {
if (!visited[i+1][j]) {
q.push(make_pair(i+1,j));
visited[i+1][j] = true;
result[i+1][j] = result[i][j] + 1;
}
}
if (j-1 >= 0) {
if (!visited[i][j-1]) {
q.push(make_pair(i,j-1));
visited[i][j-1] = true;
result[i][j-1] = result[i][j] + 1;
}
}
if (j+1 < m) {
if (!visited[i][j+1]) {
q.push(make_pair(i,j+1));
visited[i][j+1] = true;
result[i][j+1] = result[i][j] + 1;
}
}
}
}
return 0;
}
int main(void)
{
ios::sync_with_stdio(false);
cin.tie(NULL);
//freopen("input.txt", "r", stdin);
cin >> n >> m;
map.assign(n,vector<int>(m,0));
result.assign(n,vector<int>(m,0));
int t;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> t;
if (t == 2) {
x = i;
y = j;
}
map[i][j] = t;
}
}
bfs();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (map[i][j] == 1 && visited[i][j] == false) {
cout << -1 << " ";
} else {
cout << result[i][j] << " ";
}
}
cout << '\n';
}
return 0;
}