【Leetcode】733. Flood Fill

题目地址:

https://leetcode.com/problems/flood-fill/

给定一个矩阵,给定一个出发点和一个颜色值,要将其与出发点连通且与出发点颜色相同的点都染色成新的颜色。

法1:BFS。

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

public class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if (image == null || image.length == 0 || image[0].length == 0) {
            return image;
        }
        
        int color = image[sr][sc];
        boolean[][] visited = new boolean[image.length][image[0].length];
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{sr, sc});
        int[][] d = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            image[cur[0]][cur[1]] = newColor;
            visited[cur[0]][cur[1]] = true;
            for (int i = 0; i < 4; i++) {
                int newX = cur[0] + d[i][0];
                int newY = cur[1] + d[i][1];
                if (0 <= newX && newX < image.length && 0 <= newY && newY < image[0].length
                        && image[newX][newY] == color && !visited[newX][newY]) {
                    queue.offer(new int[]{newX, newY});
                }
            }
        }
        
        return image;
    }
}

法2:DFS。

public class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
        if (image == null || image.length == 0 || image[0].length == 0) {
            return image;
        }
        
        int oldColor = image[sr][sc];
        boolean[][] visited = new boolean[image.length][image[0].length];
        int[][] d = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        
        dfs(image, sr, sc, newColor, oldColor, visited, d);
        
        return image;
    }
    
    private void dfs(int[][] image, int x, int y, int newColor, int oldColor, boolean[][] visited, int[][] d) {
        image[x][y] = newColor;
        visited[x][y] = true;
    
        for (int i = 0; i < 4; i++) {
            int newX = x + d[i][0];
            int newY = y + d[i][1];
            
            if (0 <= newX && newX < image.length && 0 <= newY && newY < image[0].length
                    && image[newX][newY] == oldColor && !visited[newX][newY]) {
                dfs(image, newX, newY, newColor, oldColor, visited, d);
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值