-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShortestPath.cpp
74 lines (61 loc) · 1.71 KB
/
ShortestPath.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// { Driver Code Starts
// Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
// User function Template for C++
class Solution {
public:
struct Node {
int x, y, dist;
Node(int _x, int _y, int _dist) {
x = _x;
y = _y;
dist = _dist;
}
};
int shortestDistance(int n, int m, vector<vector<int>> A, int X, int Y) {
if (A[0][0] == 0) return -1;
int vis[n][m];
memset(vis, 0, sizeof vis);
vis[0][0] = 1;
queue<Node> q;
q.push(Node(0, 0, 0));
int dx[] = { -1, 0, 1, 0};
int dy[] = {0, 1, 0, -1};
while (!q.empty()) {
int x = q.front().x;
int y = q.front().y;
int dist = q.front().dist;
q.pop();
if (X == x && y == Y) {
return dist;
}
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
if (newX >= 0 && newY >= 0 && newX < n && newY < m
&& A[newX][newY] == 1 && vis[newX][newY] == 0) {
vis[newX][newY] = 1;
q.push(Node(newX, newY, dist+1));
}
}
}
return -1;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t--) {
int N, M, x, y;
cin >> N >> M;
vector<vector<int>> v(N, vector<int>(M));
for (int i = 0; i < N; i++)
for (int j = 0; j < M; j++) cin >> v[i][j];
cin >> x >> y;
Solution ob;
cout << ob.shortestDistance(N, M, v, x, y) << "\n";
}
} // } Driver Code Ends