Skip to content

Commit 7e3d396

Browse files
authored
Add alternative time labelling in bfs
1 parent 8ece4c8 commit 7e3d396

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

dfs-bfs.md

+24
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,30 @@ def bfs(start):
334334
q.enqueue(u)
335335
```
336336

337+
Так как мы заходим в `if` для каждой вершины лишь один раз, то метку с порядком посещения можно выставить и внутри него:
338+
339+
```python
340+
next_idx = 0
341+
342+
def bfs(start):
343+
q = queue()
344+
345+
visited[start] = True
346+
q.enqueue(start)
347+
348+
while not q.empty():
349+
v = q.dequeue()
350+
351+
for u in g[v]:
352+
if not visited[u]:
353+
visited[u] = True
354+
355+
ord[v] = next_idx # <-- вот
356+
next_idx += 1 # <-- здесь!
357+
358+
q.enqueue(u)
359+
```
360+
337361
Если хотим найти растояние в ребрах до всех вершин:
338362

339363
```python

0 commit comments

Comments
 (0)