Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b495e5c

Browse files
committed
added a new problem
1 parent 1b87a7b commit b495e5c

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

‎basic_algorithm/graph/bfs_dfs.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,55 @@ def BFS(x):
7979

8080
## 例题
8181

82+
### [walls-and-gates](https://leetcode-cn.com/problems/walls-and-gates/)
83+
84+
> 给定一个二维矩阵,矩阵中元素 -1 表示墙或是障碍物,0 表示一扇门,INF (2147483647) 表示一个空的房间。你要给每个空房间位上填上该房间到最近门的距离,如果无法到达门,则填 INF 即可。
85+
86+
**图森面试真题**。典型的多源最短路径问题,将所有源作为 BFS 的第一层即可
87+
88+
```Python
89+
inf = 2147483647
90+
91+
class Solution:
92+
def wallsAndGates(self, rooms: List[List[int]]) -> None:
93+
94+
if not rooms or not rooms[0]:
95+
return
96+
97+
M, N = len(rooms), len(rooms[0])
98+
99+
bfs = collections.deque([])
100+
101+
for i in range(M):
102+
for j in range(N):
103+
if rooms[i][j] == 0:
104+
rooms[i][j] = inf
105+
bfs.append((i, j))
106+
107+
dist = 0
108+
while bfs:
109+
num_level = len(bfs)
110+
for _ in range(num_level):
111+
r, c = bfs.popleft()
112+
if rooms[r][c] == inf:
113+
rooms[r][c] = dist
114+
115+
if r - 1 >= 0 and rooms[r - 1][c] == inf:
116+
bfs.append((r - 1, c))
117+
118+
if r + 1 < M and rooms[r + 1][c] == inf:
119+
bfs.append((r + 1, c))
120+
121+
if c - 1 >= 0 and rooms[r][c - 1] == inf:
122+
bfs.append((r, c - 1))
123+
124+
if c + 1 < N and rooms[r][c + 1] == inf:
125+
bfs.append((r, c + 1))
126+
dist += 1
127+
128+
return
129+
```
130+
82131
### [shortest-bridge](https://leetcode-cn.com/problems/shortest-bridge/)
83132

84133
> 在给定的 01 矩阵 A 中,存在两座岛 (岛是由四面相连的 1 形成的一个连通分量)。现在,我们可以将 0 变为 1,以使两座岛连接起来,变成一座岛。返回必须翻转的 0 的最小数目。

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /