【力扣】面試08.10:顏色填充 | BFS

題目描述

顏色填充。編寫函數,實現許多圖片編輯軟件都支持的“顏色填充”功能。給定一個屏幕(以二維數組表示,元素爲顏色值)、一個點和一個新的顏色值,將新顏色值填入這個點的周圍區域,直到原來的顏色值全都改變。

說明:
image 和 image[0] 的長度在範圍 [1, 50] 內。
給出的初始點將滿足 0 <= sr < image.length 和 0 <= sc < image[0].length。
image[i][j] 和 newColor 表示的顏色值在範圍 [0, 65535]

來源:力扣(LeetCode)

算法思路

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        key=image[sr][sc]
        if key==newColor:return image
        ls=[[sr,sc]]
        dire=[[0,1],[0,-1],[1,0],[-1,0]]
        m,n=len(image),len(image[0])
        image[sr][sc]=newColor
        while ls:
            for i in range(len(ls)):
                x,y=ls.pop(0)
                for j in dire:
                    x_n,y_n=x+j[0],y+j[1]
                    if 0<=x_n<m and 0<=y_n<n and image[x_n][y_n]==key:
                        image[x_n][y_n]=newColor
                        ls.append([x_n,y_n])
        return image

執行用時 :40 ms, 在所有 Python3 提交中擊敗了81.73%的用戶
內存消耗 :13.8 MB, 在所有 Python3 提交中擊敗了100.00%的用戶

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章