题目
本题难度较高。从一个起始点开始,向4个方向修改相同颜色的点成为新的颜色点,新的颜色点继续扩展。
DFS(递归):
class Solution:
def paint(self, image, sr, sc, h, w, color, newColor):
if image[sr][sc] == color:
image[sr][sc] = newColor
if sr>0:
self.paint(image, sr -1, sc, h, w, color, newColor)
if sr<h-1:
self.paint(image, sr +1, sc, h, w, color, newColor)
if sc>0:
self.paint(image, sr, sc -1, h, w, color, newColor)
if sc<w-1:
self.paint(image, sr, sc +1, h, w, color, newColor)
def floodFill(self, image, sr, sc, newColor):
if image[sr][sc] != newColor:
self.paint(image, sr, sc, len(image), len(image[0]), image[sr][sc], newColor)
return image
类似的代码
class Solution(object):
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
color=image[sr][sc]
if(color==newColor):
return image
image[sr][sc]=newColor
if(sr-1>=0 and image[sr-1][sc]==color):
image=self.floodFill(image,sr-1,sc,newColor)
if(sr+1<len(image) and image[sr+1][sc]==color):
image=self.floodFill(image,sr+1,sc,newColor)
if(sc-1>=0 and image[sr][sc-1]==color):
image=self.floodFill(image,sr,sc-1,newColor)
if(sc+1<len(image[0]) and image[sr][sc+1]==color):
image=self.floodFill(image,sr,sc+1,newColor)
return image