BFS模板

该代码实现了一个名为floodFill的函数,用于图像渲染。它接受一个二维整数数组表示的图像、起始坐标(sr,sc)和一个新的颜色值。函数使用队列进行广度优先搜索,将与起始点颜色相同的像素替换为新颜色,直到遍历完所有相邻的相同颜色像素。
摘要由CSDN通过智能技术生成

LeetCode——733. 图像渲染:

public class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int currentColor = image[sr][sc];
        if (currentColor == color) {
            return image;
        }
        Queue<int[]> queue = new LinkedList<int[]>();
        int a[] = {sr, sc};
        queue.add(a);
        int toX[] = {-1, 0, 1, 0};
        int toY[] = {0, 1, 0, -1};
        while (!queue.isEmpty()) {
            int temp[] = queue.poll();
            int tempcolor = image[temp[0]][temp[1]];
            if (tempcolor == currentColor) {
                image[temp[0]][temp[1]] = color;
                for (int i = 0; i < 4; i++) {
                    int nextX = temp[0] + toX[i];
                    int nextY = temp[1] + toY[i];
                    int next[] = {nextX, nextY};
                    if (nextX >= 0 && nextX < image.length && nextY >= 0 && nextY < image[0].length) {
                        queue.offer(next);
                    }
                }
            }
        }
        return image;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值