LeetCode 733 题
其中 DFS 的代码是 https://www.bilibili.com/video/av32546525?t=1643 看大雪菜 up主的视频,因为我 BFS 还不太会用递归的形式
BFS 是自己写的,因为可以套用模板,还是比较容易理解
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<vector>
#include<queue>
using namespace std;
vector<vector<int>> floodFill(vector<vector<int>>&image, int sr, int sc, int newColor) //DFS
{
if (image.empty() || image[0].empty())
return image;
int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 }; // 上右下左
int oldColor = image[sr][sc];
if (oldColor == newColor) // 排除走回去的情况
return image;
image[sr][sc] = newColor;
for (int i = 0; i < 4; i++)
{
int x = sr + dx[i];
int y = sc + dy[i];
if (x >= 0 && x < image.size() && y >= 0 && y < image[0].size() && image[x][y] == oldColor) // 如果下一个是旧颜色就走下去
floodFill(image, x, y, newColor);
}
return image;
}
vector<vector<int>> flood_fill(vector<vector<int>>&image, int sr, int sc, int newColor)
{
// 找到各种条件
int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 }; // 上右下左
int x = image.size(), y = image[0].size();
int oldColor = image[sr][sc];
// 初始化
image[sr][sc] = newColor;
queue<pair<int, int>> q;
pair<int, int>a(sr, sc);
q.push(a);
while (!q.empty()) // 开始 宽搜
{
pair<int, int>vertex = q.front();
q.pop();
for (int i = 0; i < 4; i++)
{
pair<int, int>next(vertex.first + dx[i], vertex.second + dy[i]);
if (next.first >= 0 && next.first < x&&next.second >= 0 && next.second < y&&image[next.first][next.second] == oldColor)
{
image[next.first][next.second] = newColor;
q.push(next);
}
}
}
return image;
}
int main(void)
{
vector<vector<int>>image(100, vector< int>(100,0)); // 初始化 行列 初始值
int sr = 1, sc = 1, newColor = 2;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
scanf("%d", &image[i][j]);
}
}
image = flood_fill(image, sr, sc, newColor);
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ", image[i][j]);
}puts("");
}
system("pause");
return 0;
}
/*测试数据
1 1 1 1 1 0 1 0 1
*/
原文:https://www.cnblogs.com/asdfknjhu/p/12457984.html