-
Notifications
You must be signed in to change notification settings - Fork 10
/
HackerEarth- Travel diaries.cpp
95 lines (84 loc) · 1.79 KB
/
HackerEarth- Travel diaries.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
#include<bits/stdc++.h>
using namespace std;
const int mx=1e3+1;
typedef pair<int,int> pi;
bool visited[mx][mx];
int dis[mx][mx];
int matrix[mx][mx];
int n,m;
vector<pi> vec={{0,1},{0,-1},{1,0},{-1,0}};
bool isvalid(int a,int b)
{
if(a>=0 && a<=n && b>=0 && b<=m && matrix[a][b] == 1)
return true;
return false;
}
void solution()
{
int x,y,xx,yy;
queue<pi>q;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(matrix[i][j]==2)
{
dis[i][j]=0;
visited[i][j]=true;
q.push(make_pair(i,j));
}
}
}
while(!q.empty())
{
pi temp=q.front();
q.pop();
x=temp.first;
y=temp.second;
for(int j=0;j<vec.size();j++)
{
xx = x+vec[j].first;
yy = y+vec[j].second;
if( isvalid(xx,yy) && visited[xx][yy]==false)
{
visited[xx][yy]=true;
dis[xx][yy]=dis[x][y]+1;
matrix[xx][yy]=2;
q.push(make_pair(xx,yy));
}
}
}
}
int main()
{
cin>>n>>m;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>matrix[i][j];
}
}
memset(visited,false,sizeof(visited));
solution();
int mx=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(matrix[i][j]==1)
{
cout<<"-1"<<endl;
return 0;
}
if(matrix[i][j]==2)
{
mx=max(mx,dis[i][j]);
}
// cout<<dis[i][j]<<" ";
}
// cout<<endl;
}
cout<<mx<<endl;
return 0;
}