问题描述:
给你一个大小为 m x n
的整数矩阵 grid
,表示一个网格。另给你三个整数 row
、col
和 color
。网格中的每个值表示该位置处的网格块的颜色。
将给定单元格[row, col]的联通区域的边界着色成color;
思路:DFS从给定单元格开始遍历,记录visited
从上下左右四个方向开始扩展,如果出界或者值不是原有颜色则是边界存到boarders中;
只要任意方向满足条件那么当前单元格就是边界,存起来;
最后统一处理进行着色;
代码:
class Solution {
public:
vector<vector<int>> colorBorder(vector<vector<int>>& grid, int row, int col, int color) {
int m = grid.size();
if(m == 0) return {};
int n = grid[0].size();
if(n == 0) return {};
int oldColor = grid[row][col];
dir = {{0,1},{0,-1},{1,0},{-1,0}};
vector<vector<int>> visited(m,vector<int>(n));
paintColor(grid,visited,row,col,color,m,n,oldColor);
for(int i = 0; i < boarders.size(); i++)
{
int r = boarders[i][0], c = boarders[i][1];
grid[r][c] = color;
}
return grid;
}
bool paintColor(vector<vector<int>>& grid, vector<vector<int>>& visited, int row, int col, int color, int m, int n, int oldColor)
{
if(row < 0 || row >= m || col < 0 || col >= n || grid[row][col] != oldColor)
{
return true;
}
if(visited[row][col])
{
return false;
}
visited[row][col] = 1;
bool isBoarder = false;
for(int i = 0; i < 4; i++)
{
isBoarder |= paintColor(grid,visited,row+dir[i][0],col+dir[i][1],color,m,n,oldColor);
}
//cout << "[" << row << "," << col <<"] is boarder" << isBoarder << endl;
if(isBoarder)
{
boarders.push_back({row,col});
}
return false;
}
private:
vector<vector<int>> dir;
vector<vector<int>> boarders;
};
题目地址:力扣