力扣: 733. 图像渲染

这篇博客介绍了如何使用Java实现图像填充功能,分别提供了基于广度优先搜索(BFS)和深度优先搜索(DFS)的两种算法。在给定的二维整数数组图像中,从指定起点开始,将颜色相同的相邻像素替换为新的颜色。代码展示了如何遍历图像并在边界检查后更新颜色。

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author xnl
 * @Description:
 * @date: 2022/6/30   23:11
 */
public class Solution {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][]  image = {{1,1,1},{1,1,0},{1,0,1}};
        int sr = 1, sc = 1, newColor = 2;
        System.out.println(solution.floodFill(image, sr, sc, newColor));
    }


    /**
     * 广度优先算法
     * @param image
     * @param sr
     * @param sc
     * @param color
     * @return
     */
    int[] dx = {1, 0, 0, -1};
    int[] dy = {0, 1, -1, 0};
    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int curCloor = image[sr][sc];
        if (curCloor == color){
            return image;
        }
        int n = image.length, m = image[0].length;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{sr, sc});
        image[sr][sc] = color;
        while (!queue.isEmpty()){
            int[] poll = queue.poll();
            int x = poll[0], y = poll[1];
            // 计算四个方向是否符合结果
            for (int i = 0; i < 4; i++){
                int mx = x + dx[i], my = y + dy[i];
                // 判断是否越界和符合条件
                if (mx >= 0 && mx < n && my >= 0 && my < m && image[mx][my] == curCloor) {
                    queue.offer(new int[]{mx, my});
                    image[mx][my] = color;
                }
            }
        }
        return image;
    }

    /**
     * 深度优先算法
     * @param image
     * @param sr
     * @param sc
     * @param color
     * @return
     */
    public int[][] floodFill2(int[][] image, int sr, int sc, int color){
        int curColor = image[sr][sc];
        if (curColor != color){
            bfs(image, sr, sc, color, curColor);
        }
        return image;
    }

    private void bfs(int[][] image, int sr, int sc ,int color, int curColor){
        image[sr][sc] = color;
        for (int i = 0; i < 4; i++){
            int x = sr + dx[i], y = sc + dy[i];
            if (x >= 0 && x < image.length && y >= 0 && y < image[0].length && image[sr][sc] == curColor){
                bfs(image, x, y, color, curColor);
            }
        }
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值