2021.09.22 - 070.图像渲染

258 篇文章 0 订阅

1. 题目

在这里插入图片描述

2. 思路

(1) DFS

  • 利用递归实现,注意要先改变当前下标的颜色再递归,否则会陷入死循环。

(2) BFS

  • 利用队列实现。

3. 代码

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

public class Test {
    public static void main(String[] args) {
        Solution1 solution = new Solution1();
        int[][] ints = solution.floodFill(new int[][]{{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}, 1, 1, 2);
        for (int[] anInt : ints) {
            for (int i : anInt) {
                System.out.println(i);
            }
            System.out.println();
        }
    }
}

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

class Solution1 {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if (newColor == image[sr][sc]) {
            return image;
        }
        int oldColor = image[sr][sc];
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{sr, sc});
        image[sr][sc] = newColor;
        while (!queue.isEmpty()) {
            int[] index = queue.poll();
            if (index[0] > 0 && image[index[0] - 1][index[1]] == oldColor) {
                queue.offer(new int[]{index[0] - 1, index[1]});
                image[index[0] - 1][index[1]] = newColor;
            }
            if (index[0] < image.length - 1 && image[index[0] + 1][index[1]] == oldColor) {
                queue.offer(new int[]{index[0] + 1, index[1]});
                image[index[0] + 1][index[1]] = newColor;
            }
            if (index[1] > 0 && image[index[0]][index[1] - 1] == oldColor) {
                queue.offer(new int[]{index[0], index[1] - 1});
                image[index[0]][index[1] - 1] = newColor;
            }
            if (index[1] < image[0].length - 1 && image[index[0]][index[1] + 1] == oldColor) {
                queue.offer(new int[]{index[0], index[1] + 1});
                image[index[0]][index[1] + 1] = newColor;
            }
        }
        return image;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值