Merge pull request #2684 from sunlight0602/105-Complete-Reachability-of-Directed-Graphs

0105.有向图的完全可达性 python BFS solution
This commit is contained in:
程序员Carl
2024-08-24 16:10:23 +08:00
committed by GitHub

View File

@ -290,6 +290,42 @@ int main() {
### Java
### Python
BFS算法
```Python
import collections
path = set() # 纪录 BFS 所经过之节点
def bfs(root, graph):
global path
que = collections.deque([root])
while que:
cur = que.popleft()
path.add(cur)
for nei in graph[cur]:
que.append(nei)
graph[cur] = []
return
def main():
N, K = map(int, input().strip().split())
graph = collections.defaultdict(list)
for _ in range(K):
src, dest = map(int, input().strip().split())
graph[src].append(dest)
bfs(1, graph)
if path == {i for i in range(1, N + 1)}:
return 1
return -1
if __name__ == "__main__":
print(main())
```
### Go