题目链接 https://leetcode.com/problems/flood-fill/
题目大意
有一幅以二维数组表示的图画,数组的每一个值代表对应的像素值,范围在0-65535之间。
给一个坐标(sr,sc) 代表图像渲染开始的初始坐标,和一个新的像素值newcolor,开始渲染这个图像。
为了上色,从初始坐标开始,记录坐标上下左右四个方向上像素值与初始坐标像素值相等的点,然后再记录满足条件的
点与它们对应四个方向上像素值与之相等的点,重复该过程。将所有被记录的点染上新的像素值newcolor。
样例 1:
Input: image = [[1,1,1],[1,1,0],[1,0,1]] sr = 1, sc = 1, newColor = 2 Output: [[2,2,2],[2,2,0],[2,0,1]] Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected by a path of the same color as the starting pixel are colored with the new color. Note the bottom corner is not colored 2, because it is not 4-directionally connected to the starting pixel.
思路:使用一个数组来模拟一个栈,使用right_index来代表数组的大小。刚开始将初始坐标加入数组,然后对数组进行遍历,每次找到一个新的满足要求的点之后,将其添加进入数组并使right_index加1,并标记为已找到,这样一来,当整个数组遍历完成之后,所有的满足要求的坐标都被找到。
代码
typedef struct node{
int x;
int y;
}Node;
int a[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};
bool good(int sr,int sc,int x,int y)
{
if(x>=0&&x<sr&&y>=0&&y<sc)
return true;
else
return false;
}
int** floodFill(int** image, int imageSize, int* imageColSize, int sr, int sc, int newColor, int* returnSize, int** returnColumnSizes){
*returnSize=imageSize;
returnColumnSizes[0]=(int*)malloc(sizeof(int)*(*returnSize));
for(int i=0;i<*returnSize;i++)
returnColumnSizes[0][i]=imageColSize[0];
Node node[3000];
int left_index = 0,right_index = 0,tmp = image[sr][sc];
node[0].x = sr;
node[0].y = sc;
for(int i=0;i<=right_index;i++)
{
for(int j=0;j<4;j++)
{
if(good(imageSize,imageColSize[0],node[i].x+a[j][0],node[i].y+a[j][1])&&image[node[i].x+a[j][0]][node[i].y+a[j][1]] == tmp)
{
right_index += 1;
node[right_index].x = node[i].x+a[j][0];
node[right_index].y = node[i].y+a[j][1];
}
}
image[node[i].x][node[i].y] = -1;
}
for(int i=0;i<imageSize;i++)
{
for(int j=0;j<imageColSize[0];j++)
{
if(image[i][j]==-1)
image[i][j] = newColor;
}
}
return image;
}