iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0
自我挑戰組

LeetCode 每日任務系列 第 20

LeetCode Day20

  • 分享至 

  • xImage
  •  

733.Flood Fill

優化版

想法:

  • 使用佇列(Queue)保存下一個要處理的像素——>先把起點放入佇列並上色
  • 每次從佇列取出一個像素→ 塗上新顏色 → 加入佇列

優勢:

避免遞迴深度過大
Java遞迴層數太深會導致 StackOverflowError,因此BFS 使用 Queue,不受遞迴限制


程式碼:

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

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int originalColor = image[sr][sc];      // 起點原始顏色
        if (originalColor == color) return image; // 若已是目標顏色則不用處理

        int rows = image.length;
        int cols = image[0].length;

        // 方向陣列:上、下、左、右
        int[][] directions = {{1,0},{-1,0},{0,1},{0,-1}};

        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{sr, sc});
        image[sr][sc] = color; // 起點先上色

        while (!queue.isEmpty()) {
            int[] current = queue.poll();
            int r = current[0];
            int c = current[1];

            // 探索四個方向
            for (int[] d : directions) {
                int nr = r + d[0];
                int nc = c + d[1];

                // 邊界與顏色檢查
                if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && image[nr][nc] == originalColor) {
                    image[nr][nc] = color;       // 塗色
                    queue.offer(new int[]{nr, nc}); // 加入佇列
                }
            }
        }

        return image;
    }
}



比較:
BFS(佇列):

  • 往一個方向一路深入直到到底,再回頭
  • 簡潔、程式短

DFS(遞迴/堆疊):

  • 一圈一圈地向外擴散
  • 安全,能避免大圖片導致遞迴爆棧

上一篇
LeetCode Day19
系列文
LeetCode 每日任務20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言