Leetcode-994 Rotting Oranges(腐烂的橘子)

 1 #define _for(i,a,b) for(int i = (a);i < (b);i ++)
 2 class Solution
 3 {
 4     public:
 5         int orangesRotting(vector<vector<int>>& grid)
 6         {
 7             int left = 0;
 8             int sz1 = grid.size();
 9             int sz2 = grid[0].size();
10             _for(i,0,sz1)
11                 _for(j,0,sz2)
12                     if(grid[i][j]==1)
13                         left ++;
14             
15             int prev = left;
16             int rnt = 0;
17             while(left)
18             {
19                 prev = left;
20                 _for(i,0,sz1)
21                     _for(j,0,sz2)
22                     {
23                         if(grid[i][j]==2)
24                         {
25                             if(i+1<sz1&&grid[i+1][j]==1)
26                             {
27                                 left--;
28                                 grid[i+1][j]=-1;
29                             }
30                             if(i-1>=0&&grid[i-1][j]==1)
31                             {
32                                 left--;
33                                 grid[i-1][j]=-1;
34                             }
35                             if(j-1>=0&&grid[i][j-1]==1)
36                             {
37                                 left--;
38                                 grid[i][j-1]=-1;
39                             }
40                             if(j+1<sz2&&grid[i][j+1]==1)
41                             {
42                                 left--;
43                                 grid[i][j+1]=-1;
44                             }
45                         }
46                     }
47                     
48                 _for(i,0,sz1)
49                     _for(j,0,sz2)
50                         if(grid[i][j]==-1)
51                             grid[i][j] = 2;
52                 rnt ++;
53                 if(prev==left)
54                     return -1;
55             }
56             return rnt;
57         }
58 };

 原则上来说,应该用BFS,看了一下数据范围,决定无脑暴力撸过

posted @ 2019-02-17 12:09  Asurudo  阅读(495)  评论(0编辑  收藏  举报