1.DFS
2.BFS
class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int precolor = image[sr][sc]; if(precolor != newColor) dfs(image, sr, sc, precolor, newColor); return image; } public void dfs(int[][] image, int row, int col, int precolor, int newcolor){ if(image[row][col] == precolor){ image[row][col] = newcolor; if(row-1 >= 0) dfs(image, row-1, col, precolor, newcolor); if(row+1 < image.length) dfs(image, row+1, col, precolor, newcolor); if(col-1 >= 0) dfs(image, row, col-1, precolor, newcolor); if(col+1 < image[0].length) dfs(image, row, col+1, precolor, newcolor); } } }
class Solution { public int[][] floodFill(int[][] image, int sr, int sc, int newColor) { int m = image.length; int n = image[0].length; int[] dx = {-1, 1, 0, 0};//搜寻附近坐标 int[] dy = {0, 0, -1, 1}; int t = n*sr + sc; //坐标换算,二维变一维 Deque<Integer> queue = new ArrayDeque<>(); Set<Integer> visited = new HashSet<>(); int preColor = image[sr][sc]; image[sr][sc] = newColor; queue.addLast(t); visited.add(t);//记录是否遍历过 while(!queue.isEmpty()){ int loc = queue.removeFirst(); int y = loc % n; int x = loc / n; for(int i = 0; i < dx.length; i++){ int nx = x+dx[i]; int ny = y+dy[i]; int nc = nx*n + ny; if(nx >= 0 && nx < m && ny >= 0 && ny < n && preColor == image[nx][ny] && !visited.contains(nc)){ image[nx][ny] = newColor; queue.addLast(nc); visited.add(nc); } } } return image; } }
Python3
class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: row = len(image) col = len(image[0]) precolor = image[sr][sc]; if precolor == newColor: return image def dfs(r, c): if image[r][c] == precolor: image[r][c] = newColor; if r-1 >= 0: dfs(r-1, c) if r+1 < row: dfs(r+1, c) if c-1 >= 0: dfs(r, c-1) if c+1 < col: dfs(r, c+1) dfs(sr, sc) return image
class Solution: def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]: row = len(image) col = len(image[0]) queue = [] visited = set() precolor = image[sr][sc] if precolor == newColor: return image image[sr][sc] = newColor queue.append((sr, sc)) visited.add((sr, sc)) while queue: x, y = queue.pop(0) for i, j in [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]: if 0<=i<row and 0<=j<col and image[i][j]==precolor and (i, j) not in visited: image[i][j] = newColor queue.append((i,j)) visited.add((i,j)) return image