面试题 08.10. 颜色填充

​​题目来源:

        leetcode题目,网址:110. 平衡二叉树 - 力扣(LeetCode)

解题思路:

       递归填充起始坐标及其四周颜色相同坐标即可。

解题代码:

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if(image[sr][sc]==newColor){
            return image;
        }
        int oldColor=image[sr][sc];
        image[sr][sc]=newColor;
        int[][] dir=new int[][]{
   
   {1,0},{0,1},{-1,0},{0,-1}};
        for(int i=0;i<4;i++){
            int newRow=sr+dir[i][0];
            int newCol=sc+dir[i][1];
            if(newRow>=0 && newCol>=0 && newRow<image.length && newCol<image[0].length && image[newRow][newCol]==oldColor){
               floodFill(image,newRow,newCol,newColor);
            }
        }
        return image;
    }
}
 
 

总结:

        注意新的颜色与原来颜色相同时的处理及不要出现死循环即可。

        官方题解给出了广度优先和深度优先时的填充,我这应该是深度优先。


猜你喜欢

转载自blog.csdn.net/2301_76145947/article/details/132443615