[Leetcode学习-java]Flood Fill(填色)

问题:

难度:easy

说明:

染色问题,将初始坐标sr,sc的颜色染成newColor,然后继续吧坐标上下左右四个地方和初始坐标一样颜色的格子一样染成newColor,再继续把染了色的格子上下左右四个和初始坐标一样颜色格子继续染色,如此类推,就是一个dfs(深扫)

输入案例:

// 在(sr,sc)就是(1,1)的地方,初始颜色为1,然后把1染成newColor 2,然后再把1上下左右四个等于1的都染色,再把染色的上下左右等于1继续染色,如此类推
image = [[1,1,1],
         [1,1,0],
         [1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],
         [2,2,0],
         [2,0,1]]

我的代码:

马上用dfs,然后拿个队列处理,写的很随意,尽快做完

class Solution {

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        // 访问标记
        int[][] visited = new int[image.length][image[0].length];

        // 直接来个放得下所有元素的队列
        int[][] queue = new int[image.length * image[0].length][2];
        // 队列头
        int begin = 0;
        // 队列末
        int end = 0;

        // 放入初始
        queue[begin] = new int[]{sr,sc};
        int re = image[sr][sc];
        visited[sr][sc] = 1;

        // 使用循环
        while(begin <= end) {
            int[] site = queue[begin ++];
            int y = site[0];
            int x = site[1];

            // 如果是一样颜色就染色
            if(image[y][x] == re) image[y][x] = newColor;

            // 上下左右四个地方
            if(y + 1 < image.length && visited[y + 1][x] != 1 && image[y + 1][x] == re) {
                queue[++ end] = new int[]{y + 1, x};
                visited[y + 1][x] = 1;
            }
            if(y - 1 >= 0 && visited[y - 1][x] != 1 && image[y - 1][x] == re) {
                queue[++ end] = new int[]{y - 1, x};
                visited[y - 1][x] = 1;
            }
            if(x + 1 < image[0].length && visited[y][x + 1] != 1 && image[y][x + 1] == re) {
                queue[++ end] = new int[]{y, x + 1};
                visited[y][x + 1] = 1;
            }
            if(x - 1 >= 0 && visited[y][x - 1] != 1 && image[y][x - 1] == re) {
                queue[++ end] = new int[]{y, x - 1};
                visited[y][x - 1] = 1;
            }
        }
        return image;
    }
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值