这是悦乐书的第306次更新,第325篇原创 <br/>算法
01 看题和准备
今天介绍的是LeetCode算法题中Easy级别的第173题(顺位题号是733)。图像由二维整数数组表示,每一个整数表示图像的像素值(从0到65535)。给定表示泛洪填充的起始像素(行和列)的坐标(sr,sc)和像素值newColor,进行“泛洪填充”图像。数组
要执行“泛洪填充”,请考虑起始像素,以及与起始像素相同颜色的起始像素4向链接的任何像素,以及与这些像素4向相连的任何像素(也使用与起始像素),依此类推。用newColor替换全部上述像素的颜色。最后,返回修改后的图像。例如:数据结构
输入:image = [[1,1,1],[1,1,0],[1,0,1]]eclipse
sr = 1,sc = 1,newColor = 2工具
输出:[[2,2,2],[2,2,0],[2,0,1]]开发工具
说明:从图像的中心(位置(sr,sc)=(1,1)),链接全部像素经过与起始像素相同颜色的路径用新颜色着色。 <br/> 注意:测试
-
图像和图像[0]的长度将在[1,50]范围内。spa
-
给定的起始像素将知足0 <= sr <image.length和0 <= sc <image [0] .length。code
-
image [i] [j]和newColor中每种颜色的值将是[0,65535]中的整数。递归
本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试。 <br/>
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); } } }
<br/>
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<int[]> queue = new LinkedList<int[]>(); 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<size; 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; }
<br/>
04 小结
算法专题目前已日更超过五个月,算法题文章174+篇,公众号对话框回复【数据结构与算法】、【算法】、【数据结构】中的任一关键词,获取系列文章合集。
以上就是所有内容,若是你们有什么好的解法思路、建议或者其余问题,能够下方留言交流,点赞、留言、转发就是对我最大的回报和支持!