-
Notifications
You must be signed in to change notification settings - Fork 0
/
7576.cpp
51 lines (46 loc) · 1.2 KB
/
7576.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
#include <iostream>
#include <queue>
using namespace std;
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int graph[1001][1001];
queue<pair<int,int> > q;
void bfs(int sx,int sy){
int date = 0;
while(!q.empty()){
int size = q.size();
date++;
for (int i = 0; i < size; i++){
int nx = q.front().first;
int ny = q.front().second;
q.pop();
for (int j = 0; j < 4; j++){
int nextx = nx + dx[j];
int nexty = ny + dy[j];
if (nextx >= 0 && nexty >= 0 && nextx < sx && nexty < sy && graph[nexty][nextx] == 0){
q.push(pair<int,int>(nextx,nexty));
graph[nexty][nextx] = 1;
}
}
}
}
for (int i = 0; i < sy; i++){
for (int j = 0; j < sx; j++){
if (graph[i][j]==0){
cout << -1;
return;
}
}
}
cout << date-1;
}
int main(){
int M,N; cin >> M >> N;
for (int i = 0; i < N; i++){
for (int j = 0; j < M; j++){
cin >> graph[i][j];
if (graph[i][j] == 1) q.push(pair<int, int>(j,i));
}
}
bfs(M,N);
}