iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0
自我挑戰組

LeetCode 每日任務系列 第 19

LeetCode Day19

  • 分享至 

  • xImage
  •  

733.Flood Fill

題目:
給定一張圖片 image(用 2D 陣列表示,每個元素是像素顏色),從起始點 (sr, sc) 開始,把所有與起始點同顏色且連通(上下左右相鄰)的像素替換成 newColor

範例:

  • Example 1:
    Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, color = 2
    Output: [[2,2,2],[2,2,0],[2,0,1]]
    Explanation:
    https://ithelp.ithome.com.tw/upload/images/20251003/201700153t6PzLox1n.png
    From the center of the image with position (sr, sc) = (1, 1) (i.e., the red
    pixel), all pixels connected by a path of the same color as the starting pixel
    (i.e., the blue pixels) are colored with the new color.
    Note the bottom corner is not colored 2, because it is not horizontally or
    vertically connected to the starting pixel.

  • Example 2:
    Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, color = 0
    Output: [[0,0,0],[0,0,0]]
    Explanation:
    The starting pixel is already colored with 0, which is the same as the target
    color. Therefore, no changes are made to the image.


想法:
像小畫家填色
從起點開始朝上下左右四方向染色(變成新的數字),當顏色與起點顏色不符時則不處理


程式碼:

class Solution {
    public int[][] floodFill(int[][] image, int sr, int sc, int color) {
        int originalColor = image[sr][sc];       //取得起點像素的原始顏色
        if (originalColor == color) return image; //如果原始顏色已經是目標顏色,就不用處理——>避免死循環

        dfs(image, sr, sc, originalColor, color); //從起點開始遞迴填色
        return image;                             //回傳已經被修改過的圖片
    }

    private void dfs(int[][] image, int r, int c, int originalColor, int color) {
        //檢查是否越界
        if (r < 0 || r >= image.length || c < 0 || c >= image[0].length) return;
        //顏色不符合,停止擴散
        if (image[r][c] != originalColor) return;

        image[r][c] = color; //把目前像素塗成新顏色

        //對四個方向擴散
        dfs(image, r + 1, c, originalColor, color); // 下
        dfs(image, r - 1, c, originalColor, color); // 上
        dfs(image, r, c + 1, originalColor, color); // 右
        dfs(image, r, c - 1, originalColor, color); // 左
    }
}


實際操作:

起點 (1,1), startColor=1, newColor=2
1 1 1
1 1 0
1 0 1

STEP1:
塗色 (1,1) → 2
往上 → (0,1)
往下 → (2,1)
往左 → (1,0)
往右 → (1,2)

STEP2:
(0,1) → 塗色 2 → 繼續擴散
(1,0) → 塗色 2 → 繼續擴散
(1,2) → 原本 0 → 不處理
(2,1) → 原本 0 → 不處理

STEP3:
繼續從 (0,1) 擴散到 (0,0), (0,2)
(0,0) → 塗色 2
(0,2) → 塗色 2
沒有新的鄰近符合顏色的點——>結束

結果:
2 2 2
2 2 0
2 0 1

https://ithelp.ithome.com.tw/upload/images/20251003/20170015AWrpoNUPjN.png


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

尚未有邦友留言

立即登入留言