-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindWhetherPathExist.cpp
More file actions
73 lines (68 loc) · 1.51 KB
/
findWhetherPathExist.cpp
File metadata and controls
73 lines (68 loc) · 1.51 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
#include <bits/stdc++.h>
using namespace std;
bool isValid(int i, int j, int n)
{
if (i >= 0 && i < n && j >= 0 && j < n)
return true;
return false;
}
int dr[] = {0, -1, 1, 0};
int dc[] = {-1, 0, 0, 1};
int bfs(pair<int, int> src, pair<int, int> dt, int n, vector<vector<int>> &v)
{
queue<pair<int, int>> q;
q.push(src);
while (!q.empty())
{
pair<int, int> temp = q.front();
q.pop();
int a, b;
for (int i = 0; i < 4; i++)
{
a = temp.first + dr[i];
b = temp.second + dc[i];
if (isValid(a, b, n))
{
if (v[a][b] == 2)
{
return true;
}
if (v[a][b] == 3)
{
q.push({a, b});
}
}
}
v[temp.first][temp.second] = 0;
}
return false;
}
int main()
{
int tc;
cin >> tc;
while (tc--)
{
int n;
cin >> n;
pair<int, int> src, dt;
vector<vector<int>> v(n, vector<int>(n, 0));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin >> v[i][j];
if (v[i][j] == 1)
{
src = {i, j};
}
if (v[i][j] == 2)
{
dt = {i, j};
}
}
}
bfs(src, dt, n, v) ? cout << 1 : cout << 0;
cout << "\n";
}
}