Skip to content

Commit d71abfa

Browse files
committed
feat: 0105 python BFS solution
1 parent 29bfd78 commit d71abfa

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

problems/kamacoder/0105.有向图的完全可达性.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,42 @@ int main() {
290290
### Java
291291

292292
### Python
293+
BFS算法
294+
```Python
295+
import collections
296+
297+
path = set() # 纪录 BFS 所经过之节点
298+
299+
def bfs(root, graph):
300+
global path
301+
302+
que = collections.deque([root])
303+
while que:
304+
cur = que.popleft()
305+
path.add(cur)
306+
307+
for nei in graph[cur]:
308+
que.append(nei)
309+
graph[cur] = []
310+
return
311+
312+
def main():
313+
N, K = map(int, input().strip().split())
314+
graph = collections.defaultdict(list)
315+
for _ in range(K):
316+
src, dest = map(int, input().strip().split())
317+
graph[src].append(dest)
318+
319+
bfs(1, graph)
320+
if path == {i for i in range(1, N + 1)}:
321+
return 1
322+
return -1
323+
324+
325+
if __name__ == "__main__":
326+
print(main())
327+
328+
```
293329

294330
### Go
295331

0 commit comments

Comments
 (0)