Skip to content

Commit 6b16638

Browse files
committed
🐱(bfs): 542. 01 矩阵
1 parent 75dd5ad commit 6b16638

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

docs/algorithm/research/bfs/README.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,93 @@ class Solution(object):
6262
return res
6363
```
6464

65+
## 542. 01 矩阵
66+
67+
[原题链接](https://leetcode-cn.com/problems/01-matrix/)
68+
69+
### BFS:以 1 为源(超时)
70+
71+
```python
72+
class Solution:
73+
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
74+
m = len(matrix)
75+
if m == 0:
76+
return []
77+
n = len(matrix[0])
78+
79+
ans = [[0 for _ in range(n)] for _ in range(m)]
80+
81+
for i in range(m):
82+
for j in range(n):
83+
if matrix[i][j] == 0:
84+
# 0 不处理
85+
continue
86+
mark = [[0 for _ in range(n)] for _ in range(m)]
87+
step = 0
88+
queue = [(i, j, step)]
89+
while len(queue) > 0:
90+
# bfs
91+
x, y, s = queue[0][0], queue[0][1], queue[0][2]
92+
del queue[0]
93+
if mark[x][y]:
94+
# 已经访问过,跳过
95+
continue
96+
# 处理
97+
mark[x][y] = 1 # 访问标记
98+
if matrix[x][y] == 0:
99+
# 找到 0,进行标记,不继续遍历
100+
ans[i][j] = s
101+
break
102+
103+
# 否则加入上下左右
104+
directions = [[0, 1], [0, -1], [-1, 0], [1, 0]]
105+
for d in directions:
106+
n_x, n_y = x + d[0], y + d[1]
107+
if n_x >= 0 and n_x < m and n_y >= 0 and n_y < n and mark[n_x][n_y] == 0:
108+
# 坐标符合要求
109+
# print(n_x, n_y, s + 1)
110+
queue.append((n_x, n_y, s + 1))
111+
112+
return ans
113+
```
114+
115+
### BFS:以 0 为源
116+
117+
把所有 0 放入队列,每个 0 逐个向外 BFS 一圈标记相邻的 1,再把 BFS 到的 1 入队列……
118+
119+
```python
120+
class Solution:
121+
def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
122+
m = len(matrix)
123+
if m == 0:
124+
return []
125+
n = len(matrix[0])
126+
127+
queue = []
128+
129+
for i in range(m):
130+
for j in range(n):
131+
# 把 0 放入队列
132+
if matrix[i][j] == 0:
133+
queue.append((i, j))
134+
else:
135+
# 把 1 标记为未访问过的结点
136+
matrix[i][j] = -1
137+
directions = [[0, 1], [0, -1], [1, 0], [-1, 0]]
138+
while len(queue) > 0:
139+
x, y = queue[0][0], queue[0][1]
140+
del queue[0]
141+
for d in directions:
142+
n_x, n_y = x + d[0], y + d[1]
143+
if n_x >= 0 and n_x < m and n_y >= 0 and n_y < n and matrix[n_x][n_y] == -1:
144+
matrix[n_x][n_y] = matrix[x][y] + 1
145+
queue.append((n_x, n_y))
146+
147+
return matrix
148+
```
149+
150+
- 时间复杂度:$O(m * n)$
151+
65152
## 1162. 地图分析
66153

67154
[原题链接](https://leetcode-cn.com/problems/as-far-from-land-as-possible/)

0 commit comments

Comments
 (0)