Leetcode-5040 Coloring A Border(边框着色)

 1 const int dx[] = {1,-1,0,0};
 2 const int dy[] = {0,0,1,-1};
 3 #define _for(i,a,b) for(int i = (a);i < (b);i ++)
 4 class Solution
 5 {
 6     public:
 7         int vis[60][60];
 8         void go(vector<vector<int>>& grid, int r0, int c0, int color,int lo)
 9         {
10             vis[r0][c0] = 1;
11             grid[r0][c0] = -color;
12             _for(i,0,4)
13             {
14                 int nx = r0 + dx[i];
15                 int ny = c0 + dy[i];
16                 if(nx>=0 && nx<grid.size() && ny>=0 && ny<grid[0].size()
17                 && vis[nx][ny]==0 && grid[nx][ny]==lo)
18                 {
19                     go(grid,nx,ny,color,lo);
20                 }
21             }
22         }
23         vector<vector<int>> colorBorder(vector<vector<int>>& grid, int r0, int c0, int color)
24         {
25             memset(vis,0,sizeof(vis));
26             int lo = grid[r0][c0];
27             go(grid,r0,c0,color,lo);
28             vector<pair<int,int>> vv;
29             _for(i,0,grid.size())
30                 _for(j,0,grid[i].size())
31                     if(grid[i][j]<0)
32                     {
33                         if(i==0 || i==grid.size()-1 || j==0 || j==grid[i].size()-1)
34                             continue;
35                         if(grid[i+1][j]==-color && grid[i-1][j]==-color && grid[i][j+1]==-color && grid[i][j-1]==-color)
36                             vv.push_back({i,j});
37                       //      grid[i][j] = lo;
38                     }
39             _for(i,0,vv.size())
40                 grid[vv[i].first][vv[i].second] = lo;
41             _for(i,0,grid.size())
42                 _for(j,0,grid[i].size())
43             {
44                 if(grid[i][j]<0)
45                     grid[i][j] = -grid[i][j];
46             }
47             
48             return grid;
49         }
50 };

 

posted @ 2019-04-28 14:34  Asurudo  阅读(364)  评论(0编辑  收藏  举报