733. Flood Fill

问题描述:给你一个int矩阵,起始坐标,sr,sc。新的数值newColor。将起始坐标数值改成newColor。并将与起始坐标上下左右相连的各个坐标,如果其值与起始坐标值相等的坐标也改成newColor,并重复此过程。简而言之,所有矩阵中与起始位置的数值相同的点。如果可以通过上下左右移动的方式到达起始位置,将数值改成newColor。
思路:递归,再利用一个数组进行是否已更改此点的记录。避免两个相邻数字都是目标值结果无限递归。
原代码:

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int val=image[sr][sc];
        int row=image.length;
        int col=image[0].length;
        int[][] record=new int[row][col];
        return floodFill(image,record,sr,sc,newColor,val);

    }

    private int[][] floodFill(int[][] image,int[][] record, int sr, int sc, int newColor, int targetValue) {
        int row=image.length;
        int col=image[0].length;
        if(sr>=0&&sr<row&&sc>=0&&sc<col){
            if(image[sr][sc]==targetValue&&record[sr][sc]==0){
                image[sr][sc]=newColor;
                record[sr][sc]=1;
                image=floodFill(image,record,sr+1,sc,newColor,targetValue);
                image=floodFill(image,record,sr-1,sc,newColor,targetValue);
                image=floodFill(image,record,sr,sc-1,newColor,targetValue);
                image=floodFill(image,record,sr,sc+1,newColor,targetValue);
                return image;
            }else
                return image;
        }else
            return image;
    }

最佳答案:

    private int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        boolean[][] visited = new boolean[image.length][image[0].length];
        helper(image, sr, sc, newColor, image[sr][sc], visited);        
        return image;
    }

    private void helper(int[][] image, int sr, int sc, int newColor, int oldColor, boolean[][] visited) {
        if (sr < 0 || sr >= image.length) {
            return;
        }
        if (sc < 0 || sc >= image[0].length) {
            return;
        }
        if (visited[sr][sc]) {
            return;
        }
        if (image[sr][sc] != oldColor) {
            return;
        }
        image[sr][sc] = newColor;
        visited[sr][sc] = true;
        for (int[] dir : dirs) {
            helper(image, sr + dir[0], sc + dir[1], newColor, oldColor, visited);
        }
    }

最佳答案中:使用boolean数组进行记录该点是否已访问。并且,还有个亮点是通过循环预定义数组来达到遍历矩阵的目的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值