733. Flood Fill

733. Flood Fill

题目描述

An image is represented by a 2-D array of integers, each integer representing the pixel value of the image (from 0 to 65535).

Given a coordinate (sr, sc) representing the starting pixel (row and column) of the flood fill, and a pixel value newColor, “flood fill” the image.

To perform a “flood fill”, consider the starting pixel, plus any pixels connected 4-directionally to the starting pixel of the same color as the starting pixel, plus any pixels connected 4-directionally to those pixels (also with the same color as the starting pixel), and so on. Replace the color of all of the aforementioned pixels with the newColor.

At the end, return the modified image.

1
2
3
4
5
6
7
8
9
10
Example 1:
Input:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
Output: [[2,2,2],[2,2,0],[2,0,1]]
Explanation:
From the center of the image (with position (sr, sc) = (1, 1)), all pixels connected
by a path of the same color as the starting pixel are colored with the new color.
Note the bottom corner is not colored 2, because it is not 4-directionally connected
to the starting pixel.

Note:

The length of image and image[0] will be in the range [1, 50].
The given starting pixel will satisfy 0 <= sr < image.length and 0 <= sc < image[0].length.
The value of each color in image[i][j] and newColor will be an integer in [0, 65535].

题目大意

经典算法:洪水填充
(sr, sc)代表起始点,改变起始点的像素,再以起始点为中心的四个方向,像素点与起始点像素相同的点作为起始点,以此类推。

解题思路

采用BFS或者DFS

代码

DFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
func floodFill(_ image: [[Int]], _ sr: Int, _ sc: Int, _ newColor: Int) -> [[Int]]
{
let dxs = [1, -1, 0, 0]
let dys = [0, 0, 1, -1]
let originColor = image[sr][sc]
func floodFillWithDFS(image: inout [[Int]], x: Int, y: Int) {
guard image[x][y] == originColor else {
return
}
image[x][y] = newColor
for (dx, dy) in zip(dxs, dys) {
let targetX = dx + x
let targetY = dy + y
guard targetX >= 0, targetX < image.count,
targetY >= 0, targetY < image[targetX].count else {
continue
}
floodFillWithDFS(image: &image, x: targetX, y: targetY)
}
}
guard image[sr][sc] != newColor else {
return image
}
var ans = image
floodFillWithDFS(image: &ans, x: sr, y: sc)
return ans
}
BFS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func floodFill(_ image: [[Int]], _ sr: Int, _ sc: Int, _ newColor: Int) -> [[Int]] {
var queue = [(sr, sc)]
let color = image[sr][sc]
let dxs = [1, -1, 0, 0]
let dys = [0, 0, 1, -1]
var ans = image
ans[sr][sc] = newColor
while !queue.isEmpty {
let (x, y) = queue.removeLast()
for (dx, dy) in zip(dxs, dys) {
let targetX = dx + x
let targetY = dy + y
guard targetX >= 0, targetX < image.count,
targetY >= 0, targetY < image[targetX].count else {
continue
}
if color == image[targetX][targetY],
ans[targetX][targetY] != newColor {
ans[targetX][targetY] = newColor
queue.append((targetX, targetY))
}
}
}
return ans
}
0%