首页 > 生活

黄哥Python: 求图中的连通分量

更新时间:2025-05-13 01:06:27 阅读: 评论:0

图中的连通分量(Connected Components in a Graph),刷题网站有如下题目。黎明离婚

1、读题,第一行有二个数字,第一个数字是顶点数n,第二个数字是边的数养老金亏空字e

2、下面的行是每行第一个数字是无向图的顶点u, 第二个数字是顶点v,这行的意思是构成一条边(u,v)

3、用Python 中字典来代表图,黄哥特别提示,先创建一个这样的图。

graph = {i:[] for i in range(1, n+1)}

medeli4、从划线平台第二行读起,添加边。

5、黄哥提剧照网醒用dfs 算法来遍历图。

6、设置一个全局变量来统计连通分量的个数。

下面看代码

'''# Sample code to perform I/O:name = input() consider的用法 # Reading input from STDINprint('Hi, %s.' % name) # Wr老毛挑iting output to STDOUT# Warning:网站关键词优化 Printing unwanted or ill-formatted data to output will cause the test cases to fail'''# Write your code heren, e = input().st英语单词记忆法rip().split()n, e = int(n), int(e)graph = {i:[] for i in range(1, n菜鸟网络+1伊能静庾澄庆)}for _ in range(e): u, v = input().strip().split() u, v 孩子流鼻血是怎么回事= int(数字时钟u), int(v) graph[u].append(v) graph[v].append(u)cc = 0visited = []stack = []def 搜狗上市dfs(graph, v): stack.append(v) 新闻专业 while stack: node = stack.pop() if node not in visited: 台湾乌龙茶 visited.append(node) e电脑常见问题lse: continue for neighbour in graph[node]: stack.append(neighbour)for v红二代 in graph: if v not in 伴热visited: cc += 1 dfs(graph,便秘了怎么办 v)print(cc)

提交后,Accepted

本文发布于:2023-05-27 13:42:11,感谢您对本站的认可!

本文链接:http://www.ranqi119.com/ge/85/136504.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:分量   图中   Python
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2022 Comsenz Inc.Powered by © 站长QQ:55-9-10-26|友情:优美诗词|电脑我帮您|扬州装修|369文学|学编程|软件玩家|水木编程|编程频道