-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathshortest path from first row to last row.cpp
More file actions
74 lines (55 loc) · 1.26 KB
/
shortest path from first row to last row.cpp
File metadata and controls
74 lines (55 loc) · 1.26 KB
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<bits/stdc++.h>
using namespace std;
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int n, m;
cin >> n >> m;
int a[n][m], dist[n][m];
queue<pair<int, int>> Q;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> a[i][j];
dist[i][j] = INT_MAX;
if (i == 0 && a[i][j]) {
Q.push({i, j});
dist[i][j] = 0;
}
}
}
while (!Q.empty()) {
int x = Q.front().first;
int y = Q.front().second;
Q.pop();
if (x == n - 1) {
break;
}
for (int i = 0; i < 4; i++) {
int xx = x + dx[i];
int yy = y + dy[i];
if (xx >= 0 && xx < n && yy >= 0 && yy < m && dist[xx][yy] == INT_MAX && a[xx][yy] == 1) {
Q.push({xx, yy});
dist[xx][yy] = dist[x][y] + 1;
}
}
// for (int i = 0; i < n; i++) {
// for (int j = 0; j < m; j++) {
// if (dist[i][j] == INT_MAX) cout << "#" << " ";
// else cout << dist[i][j] << " ";
// } cout << '\n';
// } cout << '\n';
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << dist[i][j] << " ";
} cout << '\n';
}
int minimum_distance = INT_MAX;
for (int j = 0; j < m; j++) {
minimum_distance = min(minimum_distance, dist[n - 1][j]);
}
return 0;
}