733. 图像渲染

2021/12/16 23:13:28

本文主要是介绍733. 图像渲染,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。

给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。

为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。

最后返回经过上色渲染后的图像。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flood-fill
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

import java.util.LinkedList;

class Solution {

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

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

    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        int n = image.length, m = image[0].length;
        int color = image[sr][sc];

        if (color == newColor) {
            return image;
        }

        LinkedList<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{sr, sc});
        image[sr][sc] = newColor;
        while (!queue.isEmpty()) {
            int[] node = queue.poll();
            for (int i = 0; i < 4; ++i) {
                int x = node[0] + dx[i];
                int y = node[1] + dy[i];
                if (x >= 0 && x < n && y >= 0 && y < m && image[x][y] == color) {
                    queue.offer(new int[]{x, y});
                    image[x][y] = newColor;
                }
            }
        }
        return image;
    }
}


这篇关于733. 图像渲染的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程