题目网址 list下标是从0开始的
[]是列表
()是元组
{}是集合
python变量的指向和引用
a+=a是修改a的值,其地址没变;a=a+a地址变了
主要考察的还是python的基本数据结构的使用,参考的代码和教程是这个 LeetCode版

class Solution:

    def floodFill(self, image, sr, sc, newColor):
        m = len(image)
        n = len(image[0])

        directions = [(-1,0),(1,0),(0,-1),(0,+1)]
        visited = {(sr, sc)}
        same_color = image[sr][sc]
        to_check = [(sr, sc)]
        while to_check:
            center_r,center_c = to_check.pop()
            visited.add((center_r,center_c))

            image[center_r][center_c] = newColor
            # add 4 directionally connected pixels
            for r,c in directions:
                if 0<=center_r+r<m and 0<=center_c+c<n and (center_r+r,center_c+c) not in visited and image[center_r+r][center_c+c]==same_color:
                    to_check.append((center_r+r,center_c+c))

        return image
S=Solution()
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1
sc = 1
newColor = 2
new_image=S.floodFill(image,sr,sc,newColor)
print(new_image)

image = [[0, 0, 0], [0, 0, 0]]
sr = 0
sc = 0
newColor = 2
new_image=S.floodFill(image,sr,sc,newColor)
print(new_image)

结果,可见还有提高的空间

733.Flood Fill刷题笔记_leetcode


pycharm版:

class Solution:

    def floodFill(self, image, sr, sc, newColor):
        m = len(image)
        n = len(image[0])

        directions = [(-1,0),(1,0),(0,-1),(0,+1)]
        visited = {(sr, sc)}
        same_color = image[sr][sc]
        to_check = [(sr, sc)]
        while to_check:
            center_r,center_c = to_check.pop()
            visited.add((center_r,center_c))

            image[center_r][center_c] = newColor
            # add 4 directionally connected pixels
            for r,c in directions:
                if 0<=center_r+r<m and 0<=center_c+c<n and (center_r+r,center_c+c) not in visited and image[center_r+r][center_c+c]==same_color:
                    to_check.append((center_r+r,center_c+c))

        return image
S=Solution()
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1
sc = 1
newColor = 2
new_image=S.floodFill(image,sr,sc,newColor)
print(new_image)

image = [[0, 0, 0], [0, 0, 0]]
sr = 0
sc = 0
newColor = 2
new_image=S.floodFill(image,sr,sc,newColor)
print(new_image)