60
60
61
61
## 解法
62
62
63
- ### 方法一
63
+ ### 方法一:BFS
64
+
65
+ 我们首先遍历一遍整个网格,统计出新鲜橘子的数量,记为 $\text{cnt}$,并且将所有腐烂的橘子的坐标加入队列 $q$ 中。
66
+
67
+ 接下来,我们进行广度优先搜索,每一轮搜索,我们将队列中的所有腐烂的橘子向四个方向腐烂新鲜橘子,直到队列为空或者新鲜橘子的数量为 $0$ 为止。
68
+
69
+ 最后,如果新鲜橘子的数量为 $0$,则返回当前的轮数,否则返回 $-1$。
70
+
71
+ 时间复杂度 $O(m \times n)$,空间复杂度 $O(m \times n)$。其中 $m$ 和 $n$ 分别是网格的行数和列数。
64
72
65
73
<!-- tabs:start -->
66
74
@@ -70,54 +78,53 @@ class Solution:
70
78
m, n = len (grid), len (grid[0 ])
71
79
q = deque()
72
80
cnt = 0
73
- for i in range (m):
74
- for j in range (n):
75
- if grid[i][j] == 2 :
76
- q.append((i, j))
77
- elif grid[i][j] == 1 :
81
+ for i, row in enumerate (grid):
82
+ for j, x in enumerate (row):
83
+ if x == 1 :
78
84
cnt += 1
85
+ elif x == 2 :
86
+ q.append((i, j))
87
+ dirs = (- 1 , 0 , 1 , 0 , - 1 )
79
88
ans = 0
80
89
while q and cnt:
81
90
ans += 1
82
91
for _ in range (len (q)):
83
92
i, j = q.popleft()
84
- for a, b in [[ 0 , 1 ], [ 0 , - 1 ], [ 1 , 0 ], [ - 1 , 0 ]] :
93
+ for a, b in pairwise(dirs) :
85
94
x, y = i + a, j + b
86
95
if 0 <= x < m and 0 <= y < n and grid[x][y] == 1 :
87
- cnt -= 1
88
96
grid[x][y] = 2
89
97
q.append((x, y))
90
- return ans if cnt == 0 else - 1
98
+ cnt -= 1
99
+ return - 1 if cnt > 0 else ans
91
100
```
92
101
93
102
``` java
94
103
class Solution {
95
104
public int orangesRotting (int [][] grid ) {
96
105
int m = grid. length, n = grid[0 ]. length;
106
+ Deque<int[]> q = new ArrayDeque<> ();
97
107
int cnt = 0 ;
98
- Deque<int[]> q = new LinkedList<> ();
99
108
for (int i = 0 ; i < m; ++ i) {
100
109
for (int j = 0 ; j < n; ++ j) {
101
- if (grid[i][j] == 2 ) {
102
- q. offer(new int [] {i, j});
103
- } else if (grid[i][j] == 1 ) {
110
+ if (grid[i][j] == 1 ) {
104
111
++ cnt;
112
+ } else if (grid[i][j] == 2 ) {
113
+ q. offer(new int [] {i, j});
105
114
}
106
115
}
107
116
}
117
+ final int [] dirs = {- 1 , 0 , 1 , 0 , - 1 };
108
118
int ans = 0 ;
109
- int [] dirs = {1 , 0 , - 1 , 0 , 1 };
110
- while (! q. isEmpty() && cnt > 0 ) {
111
- ++ ans;
112
- for (int i = q. size(); i > 0 ; -- i) {
113
- int [] p = q. poll();
114
- for (int j = 0 ; j < 4 ; ++ j) {
115
- int x = p[0 ] + dirs[j];
116
- int y = p[1 ] + dirs[j + 1 ];
119
+ for (; ! q. isEmpty() && cnt > 0 ; ++ ans) {
120
+ for (int k = q. size(); k > 0 ; -- k) {
121
+ var p = q. poll();
122
+ for (int d = 0 ; d < 4 ; ++ d) {
123
+ int x = p[0 ] + dirs[d], y = p[1 ] + dirs[d + 1 ];
117
124
if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 ) {
118
125
grid[x][y] = 2 ;
119
- -- cnt;
120
126
q. offer(new int [] {x, y});
127
+ -- cnt;
121
128
}
122
129
}
123
130
}
@@ -132,31 +139,29 @@ class Solution {
132
139
public:
133
140
int orangesRotting(vector<vector<int >>& grid) {
134
141
int m = grid.size(), n = grid[ 0] .size();
142
+ queue<pair<int, int>> q;
135
143
int cnt = 0;
136
- typedef pair<int, int> pii;
137
- queue<pii > q;
138
144
for (int i = 0; i < m; ++i) {
139
145
for (int j = 0; j < n; ++j) {
140
- if (grid[ i] [ j ] == 2)
141
- q.emplace(i, j);
142
- else if (grid[ i] [ j ] == 1)
146
+ if (grid[ i] [ j ] == 1) {
143
147
++cnt;
148
+ } else if (grid[ i] [ j ] == 2) {
149
+ q.emplace(i, j);
150
+ }
144
151
}
145
152
}
146
153
int ans = 0;
147
- vector<int > dirs = {-1, 0, 1, 0, -1};
148
- while (!q.empty() && cnt > 0) {
149
- ++ans;
150
- for (int i = q.size(); i > 0; --i) {
151
- auto p = q.front();
154
+ const int dirs[ 5] = {-1, 0, 1, 0, -1};
155
+ for (; q.size() && cnt; ++ans) {
156
+ for (int k = q.size(); k; --k) {
157
+ auto [ i, j] = q.front();
152
158
q.pop();
153
- for (int j = 0; j < 4; ++j) {
154
- int x = p.first + dirs[ j] ;
155
- int y = p.second + dirs[ j + 1] ;
159
+ for (int d = 0; d < 4; ++d) {
160
+ int x = i + dirs[ d] , y = j + dirs[ d + 1] ;
156
161
if (x >= 0 && x < m && y >= 0 && y < n && grid[ x] [ y ] == 1) {
157
- --cnt;
158
162
grid[ x] [ y ] = 2;
159
163
q.emplace(x, y);
164
+ --cnt;
160
165
}
161
166
}
162
167
}
@@ -167,79 +172,73 @@ public:
167
172
```
168
173
169
174
```go
170
- func orangesRotting(grid [][]int) int {
175
+ func orangesRotting(grid [][]int) (ans int) {
171
176
m, n := len(grid), len(grid[0])
177
+ q := [][2]int{}
172
178
cnt := 0
173
- var q [][]int
174
- for i := 0; i < m; i++ {
175
- for j := 0; j < n; j++ {
176
- if grid[i][j] == 2 {
177
- q = append(q, []int{i, j})
178
- } else if grid[i][j] == 1 {
179
+ for i, row := range grid {
180
+ for j, x := range row {
181
+ if x == 1 {
179
182
cnt++
183
+ } else if x == 2 {
184
+ q = append(q, [2]int{i, j})
180
185
}
181
186
}
182
187
}
183
- ans := 0
184
- dirs := []int{-1, 0, 1, 0, -1}
185
- for len(q) > 0 && cnt > 0 {
186
- ans++
187
- for i := len(q); i > 0; i-- {
188
+ dirs := [5]int{-1, 0, 1, 0, -1}
189
+ for ; len(q) > 0 && cnt > 0; ans++ {
190
+ for k := len(q); k > 0; k-- {
188
191
p := q[0]
189
192
q = q[1:]
190
- for j := 0; j < 4; j ++ {
191
- x, y := p[0]+dirs[j ], p[1]+dirs[j +1]
193
+ for d := 0; d < 4; d ++ {
194
+ x, y := p[0]+dirs[d ], p[1]+dirs[d +1]
192
195
if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 {
193
- cnt--
194
196
grid[x][y] = 2
195
- q = append(q, []int{x, y})
197
+ q = append(q, [2]int{x, y})
198
+ cnt--
196
199
}
197
200
}
198
201
}
199
202
}
200
203
if cnt > 0 {
201
204
return -1
202
205
}
203
- return ans
206
+ return
204
207
}
205
208
```
206
209
207
210
``` ts
208
211
function orangesRotting(grid : number [][]): number {
209
- const m = grid .length ;
210
- const n = grid [0 ].length ;
211
- let count = 0 ;
212
- const queue = [] ;
213
- for (let i = 0 ; i < m ; i ++ ) {
214
- for (let j = 0 ; j < n ; j ++ ) {
212
+ const m: number = grid .length ;
213
+ const n: number = grid [0 ].length ;
214
+ const q : number [][] = [] ;
215
+ let cnt : number = 0 ;
216
+ for (let i: number = 0 ; i < m ; ++ i ) {
217
+ for (let j: number = 0 ; j < n ; ++ j ) {
215
218
if (grid [i ][j ] === 1 ) {
216
- count ++ ;
219
+ cnt ++ ;
217
220
} else if (grid [i ][j ] === 2 ) {
218
- queue .push ([i , j ]);
221
+ q .push ([i , j ]);
219
222
}
220
223
}
221
224
}
222
- let res = 0 ;
223
- const dris = [1 , 0 , - 1 , 0 , 1 ];
224
- while (count !== 0 && queue .length !== 0 ) {
225
- for (let i = queue .length ; i > 0 ; i -- ) {
226
- const [x, y] = queue .shift ();
227
- for (let j = 0 ; j < 4 ; j ++ ) {
228
- const newX = x + dris [j ];
229
- const newY = y + dris [j + 1 ];
230
- if (newX >= 0 && newX < m && newY >= 0 && newY <= n && grid [newX ][newY ] === 1 ) {
231
- grid [newX ][newY ] = 2 ;
232
- queue .push ([newX , newY ]);
233
- count -- ;
225
+ let ans: number = 0 ;
226
+ const dirs: number [] = [- 1 , 0 , 1 , 0 , - 1 ];
227
+ for (; q .length && cnt ; ++ ans ) {
228
+ const t: number [][] = [];
229
+ for (const [i, j] of q ) {
230
+ for (let d = 0 ; d < 4 ; ++ d ) {
231
+ const [x, y] = [i + dirs [d ], j + dirs [d + 1 ]];
232
+ if (x >= 0 && x < m && y >= 0 && y < n && grid [x ][y ] === 1 ) {
233
+ grid [x ][y ] = 2 ;
234
+ t .push ([x , y ]);
235
+ cnt -- ;
234
236
}
235
237
}
236
238
}
237
- res ++ ;
238
- }
239
- if (count != 0 ) {
240
- return - 1 ;
239
+ q .splice (0 , q .length , ... t );
241
240
}
242
- return res ;
241
+ return cnt > 0 ? - 1 : ans ;
243
242
}
244
243
```
245
244
@@ -248,51 +247,52 @@ use std::collections::VecDeque;
248
247
249
248
impl Solution {
250
249
pub fn oranges_rotting (mut grid : Vec <Vec <i32 >>) -> i32 {
251
- let mut queue = VecDeque :: new ();
252
250
let m = grid . len ();
253
251
let n = grid [0 ]. len ();
254
- // 新鲜橘子数量
255
- let mut count = 0 ;
252
+ let mut q = VecDeque :: new ();
253
+ let mut cnt = 0 ;
254
+
256
255
for i in 0 .. m {
257
256
for j in 0 .. n {
258
- match grid [i ][j ] {
259
- 1 => {
260
- count += 1 ;
261
- }
262
- 2 => queue . push_back ([i as i32 , j as i32 ]),
263
- _ => (),
257
+ if grid [i ][j ] == 1 {
258
+ cnt += 1 ;
259
+ } else if grid [i ][j ] == 2 {
260
+ q . push_back (vec! [i as i32 , j as i32 ]);
264
261
}
265
262
}
266
263
}
267
- let mut res = 0 ;
268
- let dirs = [1 , 0 , - 1 , 0 , 1 ];
269
- while count != 0 && queue . len () != 0 {
270
- let mut len = queue . len ();
271
- while len != 0 {
272
- let [x , y ] = queue . pop_front (). unwrap ();
273
- for i in 0 .. 4 {
274
- let new_x = x + dirs [i ];
275
- let new_y = y + dirs [i + 1 ];
264
+
265
+ let dirs : [i32 ; 5 ] = [- 1 , 0 , 1 , 0 , - 1 ];
266
+ let mut ans = 0 ;
267
+
268
+ while ! q . is_empty () && cnt > 0 {
269
+ let q_size = q . len ();
270
+ for _ in 0 .. q_size {
271
+ let p = q . pop_front (). unwrap ();
272
+ for d in 0 .. 4 {
273
+ let x = p [0 ] + dirs [d ];
274
+ let y = p [1 ] + dirs [d + 1 ];
276
275
if
277
- new_x >= 0 &&
278
- new_x < (m as i32 ) &&
279
- new_y >= 0 &&
280
- new_y < (n as i32 ) &&
281
- grid [new_x as usize ][new_y as usize ] == 1
276
+ x >= 0 &&
277
+ x < (m as i32 ) &&
278
+ y >= 0 &&
279
+ y < (n as i32 ) &&
280
+ grid [x as usize ][y as usize ] == 1
282
281
{
283
- grid [new_x as usize ][new_y as usize ] = 2 ;
284
- queue . push_back ([ new_x , new_y ]);
285
- count -= 1 ;
282
+ grid [x as usize ][y as usize ] = 2 ;
283
+ q . push_back (vec! [ x , y ]);
284
+ cnt -= 1 ;
286
285
}
287
286
}
288
- len -= 1 ;
289
287
}
290
- res += 1 ;
288
+ ans += 1 ;
291
289
}
292
- if count != 0 {
290
+
291
+ if cnt > 0 {
293
292
return - 1 ;
294
293
}
295
- res
294
+
295
+ ans
296
296
}
297
297
}
298
298
```
0 commit comments