Skip to content

Commit dda7ab1

Browse files
committed
bfs 733
1 parent 8e80f33 commit dda7ab1

File tree

2 files changed

+113
-0
lines changed

2 files changed

+113
-0
lines changed

go/bfs-dfs/733/733.图像渲染.go

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
/*
2+
* @lc app=leetcode.cn id=733 lang=golang
3+
*
4+
* [733] 图像渲染
5+
*
6+
* https://leetcode.cn/problems/flood-fill/description/
7+
*
8+
* algorithms
9+
* Easy (58.56%)
10+
* Likes: 415
11+
* Dislikes: 0
12+
* Total Accepted: 147.9K
13+
* Total Submissions: 252.2K
14+
* Testcase Example: '[[1,1,1],[1,1,0],[1,0,1]]\n1\n1\n2'
15+
*
16+
* 有一幅以 m x n 的二维整数数组表示的图画 image ,其中 image[i][j] 表示该图画的像素值大小。
17+
*
18+
* 你也被给予三个整数 sr ,  sc 和 newColor 。你应该从像素 image[sr][sc] 开始对图像进行 上色填充 。
19+
*
20+
* 为了完成 上色工作 ,从初始像素开始,记录初始坐标的 上下左右四个方向上
21+
* 像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应 四个方向上
22+
* 像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为 newColor 。
23+
*
24+
* 最后返回 经过上色渲染后的图像 。
25+
*
26+
*
27+
*
28+
* 示例 1:
29+
*
30+
*
31+
*
32+
*
33+
* 输入: image = [[1,1,1],[1,1,0],[1,0,1]],sr = 1, sc = 1, newColor = 2
34+
* 输出: [[2,2,2],[2,2,0],[2,0,1]]
35+
* 解析: 在图像的正中间,(坐标(sr,sc)=(1,1)),在路径上所有符合条件的像素点的颜色都被更改成2。
36+
* 注意,右下角的像素没有更改为2,因为它不是在上下左右四个方向上与初始点相连的像素点。
37+
*
38+
*
39+
* 示例 2:
40+
*
41+
*
42+
* 输入: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 2
43+
* 输出: [[2,2,2],[2,2,2]]
44+
*
45+
*
46+
*
47+
*
48+
* 提示:
49+
*
50+
*
51+
* m == image.length
52+
* n == image[i].length
53+
* 1 <= m, n <= 50
54+
* 0 <= image[i][j], newColor < 2^16
55+
* 0 <= sr < m
56+
* 0 <= sc < n
57+
*
58+
*
59+
*/
60+
package jzoffer
61+
62+
// @lc code=start
63+
func floodFill(image [][]int, sr int, sc int, color int) [][]int {
64+
type point struct {
65+
x, y int
66+
}
67+
preColor := image[sr][sc] // 记录初始颜色
68+
69+
queue := []point{{sr, sc}}
70+
visited := make(map[point]bool)
71+
72+
// 查找邻居
73+
neighbors := func(p point) (points []point) {
74+
ps := []point{{p.x, p.y - 1}, {p.x, p.y + 1}, {p.x - 1, p.y}, {p.x + 1, p.y}}
75+
for _, v := range ps {
76+
if v.x >= 0 && v.x < len(image) &&
77+
v.y >= 0 && v.y < len(image[0]) {
78+
if !visited[v] && image[v.x][v.y] == preColor {
79+
points = append(points, v)
80+
}
81+
}
82+
}
83+
return
84+
}
85+
for len(queue) > 0 {
86+
top := queue[len(queue)-1]
87+
queue = queue[:len(queue)-1]
88+
if visited[top] {
89+
continue
90+
}
91+
image[top.x][top.y] = color
92+
visited[top] = true
93+
queue = append(queue, neighbors(top)...)
94+
95+
}
96+
return image
97+
}
98+
99+
// @lc code=end

go/bfs-dfs/733/733_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package jzoffer
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
func Test733(t *testing.T) {
9+
// [[1,1,1],[1,1,0],[1,0,1]]
10+
// 1
11+
// 1
12+
// 2
13+
fmt.Println(floodFill([][]int{{1, 1, 1}, {1, 1, 0}, {1, 0, 1}}, 1, 1, 2))
14+
}

0 commit comments

Comments
 (0)