File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ int maxDistance (vector<vector<int >>& grid) {
4
+ queue<pair<int ,int >> q;
5
+ int steps = 0 ,r = grid.size (),c = grid[0 ].size ();
6
+
7
+ for (int i = 0 ; i < r; i++) {
8
+ for (int j = 0 ; j < c; j++) {
9
+ if (grid[i][j] == 1 ) {
10
+ q.push ({i-1 , j});
11
+ q.push ({i+1 , j});
12
+ q.push ({i, j-1 });
13
+ q.push ({i, j+1 });
14
+ }
15
+ }
16
+ }
17
+ while (!q.empty ()) {
18
+ int size = q.size ();
19
+ steps++;
20
+ for (int k = 0 ; k < size; k++) {
21
+ int i = q.front ().first , j = q.front ().second ;
22
+ q.pop ();
23
+ if (i >= 0 && j >= 0 && i < r && j < c&& grid[i][j] == 0 ) {
24
+ grid[i][j] = steps;
25
+ q.push ({i-1 , j});
26
+ q.push ({i+1 , j});
27
+ q.push ({i, j-1 });
28
+ q.push ({i, j+1 });
29
+ }
30
+ }
31
+ }
32
+ return steps == 1 ? -1 : steps - 1 ;
33
+ }
34
+ };
You can’t perform that action at this time.
0 commit comments