-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDijkstra_In_Grid.cpp
128 lines (100 loc) · 2.31 KB
/
Dijkstra_In_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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
//AnkitCode99 here....
//every ups and downs matter!
#include<bits/stdc++.h>
#define endl "\n"
#define IOS ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr)
typedef long long int ll;
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define pb push_back
using namespace std;
const ll sz=1e5+5;
const ll szz=1e6+6;
const ll mod=1e9+7;
vector<string> grid;
// Dijkstra in GRID
ll dx[]={-1,0,1,0};
ll dy[]={0,-1,0,1};
bool isValid(ll x,ll y,ll row,ll col)
{
return (x>=0 and x<row and y>=0 and y<col);
}
void dijkstra()
{
ll n = grid.size();
ll m = grid[0].size();
ll dist[n][m];
rep(i,0,n)
{
rep(j,0,m)
{
dist[i][j] = 1e15;
}
}
bool vis[n][m];
memset(vis,0,sizeof vis);
vis[0][0]=1;
dist[0][0]=0;
queue<pair<ll,ll>> q;
q.push({0,0});
// cout<<"Fine\n";
// return;
while(!q.empty())
{
auto it = q.front();
q.pop();
if(it.first==(n-1) and it.second==(m-1))
{
break;
}
for(ll i=0;i<4;i++)
{
ll nx = it.first + dx[i];
ll ny = it.second + dy[i];
// cout<<nx<<" "<<ny<<endl;
if(isValid(nx,ny,n,m))
{
if(!vis[nx][ny] and grid[nx][ny]=='.')
{
dist[nx][ny] = dist[it.first][it.second]+1;
vis[nx][ny]=1;
q.push({nx,ny});
}
}
// if(!vis[nx][ny] and grid[nx][ny]=='.' and isValid(nx,ny,n,m))
// {
// cout<<nx<<" "<<ny<<endl;
// // dist[nx][ny] = dist[it.first][it.second]+1;
// // vis[nx][ny]=1;
// q.push({nx,ny});
// }
}
}
rep(i,0,n)
{
rep(j,0,m)
{
cout<<dist[i][j]<<"\t";
}
cout<<endl;
}
}
int main()
{
IOS;
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("op.txt","w",stdout);
#endif
clock_t startTime=clock();
ll n;
cin>>n;
rep(i,0,n)
{
string s;
cin>>s;
grid.pb(s);
}
// cout<<"entered\n";
dijkstra();
cerr << endl <<setprecision(20)<< double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;
}//Goodbye...