1+ #include < iostream>
2+ #include < vector>
3+ #include < queue>
4+
5+ using namespace std ;
6+
7+ struct Node {
8+ int x=0 ;
9+ int y=0 ;
10+ int day =0 ;
11+ bool visited = false ;
12+
13+ Node () {}
14+
15+ Node (int x, int y, int day)
16+ : x(x), y(y), day(day) {}
17+
18+ Node (int x, int y, int day, bool visited)
19+ : x(x), y(y), day(day), visited(visited) {}
20+
21+ };
22+
23+ void ppp (vector<vector<Node>> map) {
24+ cout << " =====================" << endl;
25+ for (int i = 0 ; i < 4 ; i++) {
26+ for (int j = 0 ; j < 6 ; j++) {
27+ cout << map[i][j].day << " " ;
28+ }
29+ cout << ' \n ' ;
30+ }
31+ }
32+
33+
34+ int main () {
35+ freopen_s (new FILE *, " input.txt" , " r" , stdin);
36+ ios::sync_with_stdio (false );
37+ cin.tie (nullptr );
38+
39+ int row, col;
40+ cin >> col >> row;
41+ vector<vector<Node>> map (row, vector<Node>(col));
42+ queue<Node> q;
43+
44+ int dx[] = { -1 , 0 , 1 , 0 };
45+ int dy[] = { 0 , 1 , 0 , -1 };
46+
47+ bool cho = false ;
48+
49+ for (int i = 0 ; i < row; i++) {
50+ for (int j = 0 ; j < col; j++) {
51+ int state;
52+ cin >> state;
53+ if (state == 0 ) cho = true ;
54+ else if (state == 1 ) q.push ({ i,j,1 });
55+ map[i][j] = {i, j, state, state==-1 ? true :false };
56+ }
57+ }
58+
59+ if (cho == false ) {
60+ cout << 0 ;
61+ return 0 ;
62+ }
63+
64+
65+
66+ while (!q.empty ())
67+ {
68+ Node currentNode = q.front ();
69+ q.pop ();
70+ for (int k = 0 ; k < 4 ; k++) {
71+ int nx = currentNode.x + dx[k];
72+ int ny = currentNode.y + dy[k];
73+
74+ if (nx < 0 || nx >= row || ny < 0 || ny >= col) continue ;
75+ if (currentNode.visited ) continue ;
76+
77+ int nday = currentNode.day + 1 ;
78+ if (nday >= map[nx][ny].day && map[nx][ny].day != 0 ) continue ;
79+ map[nx][ny].day = nday;
80+ q.push ({ nx, ny, nday });
81+ }
82+ map[currentNode.x ][currentNode.y ].visited = true ;
83+
84+ // ppp(map);
85+ }
86+
87+ bool notall = false ;
88+ int max = 0 ;
89+ for (int i = 0 ; i < row; i++) {
90+ for (int j = 0 ; j < col; j++) {
91+ if (map[i][j].day == 0 ) {
92+ cout << -1 ;
93+ notall = true ;
94+ break ;
95+ }
96+ if (max <= map[i][j].day ) max = map[i][j].day ;
97+ }
98+ if (notall == true ) return 0 ;
99+ }
100+
101+ cout << max-1 ;
102+
103+
104+ return 0 ;
105+ }
0 commit comments