FloodFill算法简介:
在一个有山谷平原低谷的地区,有洪水,然后找出会被洪水淹没的地区。
其实就是在找一个性质相同的连通块。
1、图像渲染
class Solution
{
bool visit[51][51];
int aim;//目标像素
int init;//原始像素
int dx[4] = {0,0,1,-1};
int dy[4] = {1,-1,0,0};
int m,n;
public:
vector<vector<int>> floodFill(vector<vector<int>>& image, int sr, int sc, int color)
{
aim = color;
init = image[sr][sc];
if(init == aim) return image;//如果初始像素就等于原始像素,就不用操作
m = image.size(), n = image[0].size();
dfs(image,sr,sc);
return image;
}
void dfs(vector<vector<int>>& image,int i,int j)
{
image[i][j] = aim;//将该位置改为aim
for(int k = 0;k<4;k++)
{
int x = i + dx[k], y = j + dy[k];
if(x >= 0 && x < m && y >= 0 && y < n && !visit[x][y] && image[x][y] == init)//满足条件
{
dfs(image,x,y);//就递归进去
}
}
}
};
注意:这道题的话,不需要用visit来记录路径,这个题是可以退回去使用的,我们需要做的只是将像素改变。
并且,我们到达一个“路口”的时候,向不同岔路口进去遍历后,是需要回到当前路口的。如果用visit的话,就回不来了。因为这里只用修改现场,不用恢复。
2、岛屿数量
那么其实本题就是找有几块“1”,就可以使用FloodFill算法。
class Solution
{
int m,n;
int res;//统计岛屿数量
int dx[4] = {0,0,1,-1};//向量表示
int dy[4] = {1,-1,0,0};
vector<vector<bool>> visit;//记录走过的陆地,就不能还原现场了
public:
int numIslands(vector<vector<char>>& grid)
{
m = grid.size(), n = grid[0].size();
visit = vector<vector<bool>>(m,vector<bool>(n,false));
for(int i = 0; i < m ;i++)
for(int j = 0 ;j<