Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- #define ii pair<int, int>
- #define fi first
- #define se second
- int n, m;
- int M[600][600];
- int dist[600][600];
- bool check(int x, int y) {
- return x >= 0 and x < n and y >= 0 and y < m;
- }
- int bfs() {
- queue<ii> q;
- q.push({0, 0});
- memset(dist, -1, sizeof(dist));
- dist[0][0] = 0;
- while(!q.empty()) {
- ii a = q.front();
- q.pop();
- for(int i = -2; i <= 2; i++)
- for(int j = -2; j <= 2; j++) {
- if(!i and !j) continue;
- int x = i + a.fi, y = j + a.se;
- if(check(x, y) and dist[x][y] == -1 and M[x][y]) {
- dist[x][y] = dist[a.fi][a.se] + 1;
- q.push({x, y});
- }
- }
- }
- return dist[n - 1][m - 1];
- }
- int32_t main()
- {
- cin >> n >> m;
- for(int i = 0; i < n; i++)
- for(int j = 0; j < m; j++)
- cin >> M[i][j];
- cout << bfs() << '\n';
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement