-
Notifications
You must be signed in to change notification settings - Fork 8
/
bfs-on-a-grid.cpp
93 lines (90 loc) · 2.24 KB
/
bfs-on-a-grid.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
#define mkp make_pair
int main() {
ll t;
cin>>t;
while(t--)
{
ll n,m;
cin>>n>>m;
ll a[n+1][m+1];
ll v[(n*m)+1];
for(ll i=1;i<=(n*m);i++)
{
cin>>v[i];
}
ll k=1;
for(ll i=1;i<=n;i++)
{
for(ll j=1;j<=m;j++)
{
a[i][j]=v[k];
k++;
}
}
ll u1,v1;
cin>>u1>>v1;
ll dist[n+1][m+1];
for(ll i=1;i<=n;i++)
{
for(ll j=1;j<=m;j++)
dist[i][j]=INT_MAX;
}
queue<pair<ll,ll> > q;
if(a[1][1]==1)
{
q.push(mkp(1,1));
dist[1][1]=0;
while(!q.empty())
{
ll x=q.front().first;
ll y=q.front().second;
q.pop();
if(y+1<=m && a[x][y+1]==1)
{
if(dist[x][y]+1<dist[x][y+1])
{
dist[x][y+1]=dist[x][y]+1;
q.push(mkp(x,y+1));
}
}
if(y-1>=1 && a[x][y-1]==1)
{
if(dist[x][y]+1<dist[x][y-1])
{
dist[x][y-1]=dist[x][y]+1;
q.push(mkp(x,y-1));
}
}
if(x-1>=1 && a[x-1][y]==1)
{
if(dist[x][y]+1<dist[x-1][y])
{
dist[x-1][y]=dist[x][y]+1;
q.push(mkp(x-1,y));
}
}
if(x+1<=n && a[x+1][y]==1)
{
if(dist[x][y]+1<dist[x+1][y])
{
dist[x+1][y]=dist[x][y]+1;
q.push(mkp(x+1,y));
}
}
}
}
for(ll i=1;i<=n;i++)
{
for(ll j=1;j<=m;j++)
{
if(dist[i][j]==INT_MAX)
dist[i][j]=-1;
}
}
cout<<dist[u1+1][v1+1]<<endl;
}
return 0;
}