算法练习-LeetCoe 733. Flood Fill
创始人
2024-05-26 16:09:08
0

题目地址:https://leetcode.com/problems/flood-fill/description/

解题思路:深度优先搜索

code(java):

public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {int oldColor = image[sr][sc];if (oldColor == newColor) {return image;}fill(image, sr, sc, oldColor, newColor);return image;
}private void fill(int[][] image, int row, int col, int oldColor, int newColor) {if (row < 0 || row >= image.length || col < 0 || col >= image[0].length || image[row][col] != oldColor) {return;}image[row][col] = newColor;fill(image, row - 1, col, oldColor, newColor);fill(image, row + 1, col, oldColor, newColor);fill(image, row, col - 1, oldColor, newColor);fill(image, row, col + 1, oldColor, newColor);
}

This method takes a 2D integer array image, two integers sr and sc, and an integer newColor as input, and returns the modified image after performing the flood fill. It first checks if the oldColor at the starting pixel image[sr][sc] is equal to the newColor, and returns the image if they are equal. Otherwise, it calls a helper method fill to perform the flood fill. The fill method performs a depth-first search on the image starting from the pixel (row, col), and replaces the oldColor with the newColor at each visited pixel. It recursively calls itself on the neighboring pixels of the current pixel that have the same oldColor.

For example, if image is the following 2D integer array:

[[1,1,1],[1,1,0],[1,0,1]]

And we call floodFill(image, 1, 1, 2), the method will perform the flood fill starting from the pixel (1, 1) with oldColor 1 and newColor 2. The resulting image will be:

[[2,2,2],[2,2,0],[2,0,1]]

相关内容

热门资讯

喜欢穿一身黑的男生性格(喜欢穿... 今天百科达人给各位分享喜欢穿一身黑的男生性格的知识,其中也会对喜欢穿一身黑衣服的男人人好相处吗进行解...
发春是什么意思(思春和发春是什... 本篇文章极速百科给大家谈谈发春是什么意思,以及思春和发春是什么意思对应的知识点,希望对各位有所帮助,...
网络用语zl是什么意思(zl是... 今天给各位分享网络用语zl是什么意思的知识,其中也会对zl是啥意思是什么网络用语进行解释,如果能碰巧...
为什么酷狗音乐自己唱的歌不能下... 本篇文章极速百科小编给大家谈谈为什么酷狗音乐自己唱的歌不能下载到本地?,以及为什么酷狗下载的歌曲不是...
华为下载未安装的文件去哪找(华... 今天百科达人给各位分享华为下载未安装的文件去哪找的知识,其中也会对华为下载未安装的文件去哪找到进行解...
怎么往应用助手里添加应用(应用... 今天百科达人给各位分享怎么往应用助手里添加应用的知识,其中也会对应用助手怎么添加微信进行解释,如果能...
家里可以做假山养金鱼吗(假山能... 今天百科达人给各位分享家里可以做假山养金鱼吗的知识,其中也会对假山能放鱼缸里吗进行解释,如果能碰巧解...
四分五裂是什么生肖什么动物(四... 本篇文章极速百科小编给大家谈谈四分五裂是什么生肖什么动物,以及四分五裂打一生肖是什么对应的知识点,希...
一帆风顺二龙腾飞三阳开泰祝福语... 本篇文章极速百科给大家谈谈一帆风顺二龙腾飞三阳开泰祝福语,以及一帆风顺二龙腾飞三阳开泰祝福语结婚对应...
美团联名卡审核成功待激活(美团... 今天百科达人给各位分享美团联名卡审核成功待激活的知识,其中也会对美团联名卡审核未通过进行解释,如果能...