floodfill算法 java_LeetCode算法题-Flood Fill(Java实现)

这是悦乐书的第306次更新,第325篇原创

01 看题和准备

今天介绍的是LeetCode算法题中Easy级别的第173题(顺位题号是733)。图像由二维整数数组表示,每个整数表示图像的像素值(从0到65535)。给定表示泛洪填充的起始像素(行和列)的坐标(sr,sc)和像素值newColor,进行“泛洪填充”图像。

要执行“泛洪填充”,请考虑起始像素,以及与起始像素相同颜色的起始像素4向连接的任何像素,以及与这些像素4向相连的任何像素(也使用与起始像素),依此类推。用newColor替换所有上述像素的颜色。最后,返回修改后的图像。例如:

输入:image = [[1,1,1],[1,1,0],[1,0,1]]

sr = 1,sc = 1,newColor = 2

输出:[[2,2,2],[2,2,0],[2,0,1]]

说明:从图像的中心(位置(sr,sc)=(1,1)),连接所有像素通过与起始像素相同颜色的路径用新颜色着色。

注意:

图像和图像[0]的长度将在[1,50]范围内。

给定的起始像素将满足0 <= sr

image [i] [j]和newColor中每种颜色的值将是[0,65535]中的整数。

本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。

02 第一种解法

题目的意思是将起始位置的值改为新的值,如果值不相同的话。并且以起始坐标开始,其上下左右四个方向的点,如果像素值和起始坐标的相等,也要改为新的坐标值,以这些四个方向上的点也会继续向他们本身的四个方向延伸,直到不能修改为止。

上述问题的子问题与问题本身的性质一样,都是以本身为中心,向四个方向扩散,因此我们可以借助递归来实现,但是需要注意边界,不要下标越界了。

public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {

int oldColor = image[sr][sc];

if (oldColor != newColor) {

help(image, sr, sc, newColor, oldColor);

}

return image;

}

public void help(int[][] image, int sr, int sc, int newColor, int oldColor) {

if (image[sr][sc] == oldColor) {

image[sr][sc] = newColor;

// 向上

if (sr-1 >= 0) {

help(image, sr-1, sc, newColor, oldColor);

}

// 向下

if (sr+1 < image.length) {

help(image, sr+1, sc, newColor, oldColor);

}

// 向左

if (sc-1 >= 0) {

help(image, sr, sc-1, newColor, oldColor);

}

// 向右

if (sc+1 < image[0].length) {

help(image, sr, sc+1, newColor, oldColor);

}

}

}

03 第二种解法

我们也可以使用迭代的方式来实现,借助队列。队列中存放的是坐标,以数组形式表现,另外将四个方向用两个坐标数组来表示,x表示行的方向,y表示列的方向。在队列中判断四个方向的数据是否符合要求,不能越界并且要等于原始起点的值,将满足这些条件的坐标存入数组。

public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {

int oldColor = image[sr][sc];

if (oldColor == newColor) {

return image;

}

Queue queue = new LinkedList();

queue.offer(new int[]{sr, sc});

int[] x = {1,-1,0,0};

int[] y = {0,0,1,-1};

while (!queue.isEmpty()) {

int size = queue.size();

for (int i=0; i

int[] temp = queue.poll();

int m = temp[0];

int n = temp[1];

image[m][n] = newColor;

for (int j=0; j<4; j++) {

int nx = x[j]+m;

int ny = y[j]+n;

if (nx>=image.length || nx<0 || ny>=image[0].length || ny<0 || image[nx][ny] != oldColor) {

continue;

}

queue.offer(new int[]{nx, ny});

}

}

}

return image;

}

04 小结

算法专题目前已日更超过五个月,算法题文章174+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。

以上就是全部内容,如果大家有什么好的解法思路、建议或者其他问题,可以下方留言交流,点赞、留言、转发就是对我最大的回报和支持!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值