-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathhyeongjun.cpp
55 lines (54 loc) · 1.5 KB
/
hyeongjun.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
#include <bits/stdc++.h>
using namespace std;
#define fastio cin.tie(0)->sync_with_stdio(0)
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
int n, m;
string a[100];
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
int dist[100][100];
int main() {
fastio;
cin >> m >> n;
for(int i = 0; i < n; i++) {
cin >> a[i];
}
memset(dist, -1, sizeof(dist));
queue<pii> q;
q.emplace(0, 0);
dist[0][0] = 0;
while(!q.empty()) {
auto [x, y] = q.front();
q.pop();
for(int k = 0; k < 4; k++) {
int nx = x + dx[k];
int ny = y + dy[k];
if(nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
if(a[nx][ny] == '1') {
if(dist[nx][ny] == -1) {
dist[nx][ny] = dist[x][y] + 1;
q.emplace(nx, ny);
} else {
if(dist[nx][ny] > dist[x][y] + 1) {
dist[nx][ny] = dist[x][y] + 1;
q.emplace(nx, ny);
}
}
} else {
if(dist[nx][ny] == -1) {
dist[nx][ny] = dist[x][y];
q.emplace(nx, ny);
} else {
if(dist[nx][ny] > dist[x][y]) {
dist[nx][ny] = dist[x][y];
q.emplace(nx, ny);
}
}
}
}
}
cout << dist[n - 1][m - 1] << '\n';
return 0;
}