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);
}
}
}
}
力扣: 733. 图像渲染
最新推荐文章于 2025-12-01 18:34:51 发布
这篇博客介绍了如何使用Java实现图像填充功能,分别提供了基于广度优先搜索(BFS)和深度优先搜索(DFS)的两种算法。在给定的二维整数数组图像中,从指定起点开始,将颜色相同的相邻像素替换为新的颜色。代码展示了如何遍历图像并在边界检查后更新颜色。
522

被折叠的 条评论
为什么被折叠?



