Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include<vector>
- #include<queue>
- using namespace std;
- int main() {
- int n = 0, m = 0, x0 = 0, y0 = 0, x1 = 0, y1 = 0;
- cin >> n >> m;
- vector<vector<int> > v(n, vector<int>(m, n * m));
- for (int i = 0; i < n; i++)
- {
- for (int j = 0; j < m; j++)
- {
- int x;
- cin >> x;
- if (x != 0)
- v[i][j] = -1;
- }
- }
- cin >> x0 >> y0 >> x1 >> y1;
- x0--; y0--; x1--; y1--;
- v[y0][x0] = 0;
- queue<pair<int, int> > q;
- q.push({ y0, x0 });
- while (!q.empty()) {
- int y = q.front().first;
- int x = q.front().second;
- q.pop();
- if (x - 1 >= 0 && v[y][x] + 1 < v[y][x -1] && v[y][x -1] != -1) {
- v[y][x-1] = v[y][x] + 1;
- q.push({ y,x - 1 });
- }
- if (x + 1 < m && v[y][x] + 1 < v[y][x + 1] && v[y ][x + 1] != -1) {
- v[y][x + 1] = v[y][x] + 1;
- q.push({y, x + 1});
- }
- if (y - 1 >= 0 && v[y][x] + 1 < v[y - 1][x] && v[y - 1][x] != -1) {
- v[y -1][x] = v[y][x] + 1;
- q.push({ y - 1 ,x});
- }
- if (y + 1 < n && v[y][x] + 1 < v[y + 1][x] && v[y + 1][x] != -1) {
- v[y + 1][x] = v[y][x] + 1;
- q.push({ y + 1,x });
- }
- }
- if (v[y1][x1] == m * n || v[y1][x1] == -1)
- cout << -1;
- else
- cout << v[y1][x1];
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement