1
+ // 基本思路是使用广度优先搜索进行加速
2
+ // Runtime: 4 ms, faster than 94.02% of C++ online submissions for Rotting Oranges.
3
+ // Memory Usage: 9.1 MB, less than 81.25% of C++ online submissions for Rotting Oranges.
4
+
5
+ class Solution
6
+ {
7
+ public:
8
+ int orangesRotting (vector<vector<int >>& grid)
9
+ {
10
+ // 边界条件处理
11
+ int row = grid.size ();
12
+ if (row == 0 ) return -1 ;
13
+
14
+ int col = grid[0 ].size ();
15
+ if (col == 0 ) return -1 ;
16
+
17
+ // 首先纳入已经坏掉的橘子的坐标
18
+ int numOfFresh = 0 ;
19
+ int numOfRotten = 0 ;
20
+ queue<pair<int , int >> poss;
21
+ for (int i = 0 ; i < row; ++i)
22
+ {
23
+ for (int j = 0 ; j < col; ++j)
24
+ {
25
+ if (grid[i][j] == 1 )
26
+ {
27
+ ++numOfFresh;
28
+ }
29
+
30
+ if (grid[i][j] == 2 )
31
+ {
32
+ ++numOfRotten;
33
+ poss.push (make_pair (i, j));
34
+ }
35
+ }
36
+ }
37
+
38
+ // 边界条件处理
39
+ if (numOfFresh == 0 && numOfRotten == 0 )
40
+ return 0 ;
41
+ if (numOfFresh == 0 && numOfRotten != 0 )
42
+ return 0 ;
43
+ if (numOfFresh != 0 && numOfRotten == 0 )
44
+ return -1 ;
45
+
46
+ // BFS
47
+ int layer = 0 ;
48
+ int offsetx[] = {-1 , 1 , 0 , 0 };
49
+ int offsety[] = {0 , 0 , -1 , 1 };
50
+ while (!poss.empty ())
51
+ {
52
+ for (int i = poss.size (); i > 0 ; --i)
53
+ {
54
+ auto pos = poss.front ();
55
+ poss.pop ();
56
+
57
+ for (int j = 0 ; j < 4 ; ++j)
58
+ {
59
+ int newx = pos.first + offsetx[j];
60
+ int newy = pos.second + offsety[j];
61
+ if (newx >= 0 && newx < row && newy >= 0 && newy < col && grid[newx][newy] == 1 )
62
+ {
63
+ grid[newx][newy] = 2 ;
64
+ poss.push (make_pair (newx, newy));
65
+
66
+ --numOfFresh;
67
+ ++numOfRotten;
68
+ }
69
+ }
70
+ }
71
+ ++layer;
72
+ }
73
+
74
+ if (numOfFresh == 0 )
75
+ return layer - 1 ;
76
+ else
77
+ return -1 ;
78
+ }
79
+ };
0 commit comments