wordpress站群版,家庭宽带做网站服务器吗,泉州网站建设手机,wordpress 文章备份题目链接
题目中给了邻接链表#xff0c;转为邻接矩阵初始化邻接矩阵 graph [[] for _ in range(n)]dfs() 的写法#xff0c; 用visi避免重复访问#xff0c;得到每个点所在的联通分量中点的个数
class Solution:def countPairs(self, n: int, edges: List[List[int]]) -…题目链接
题目中给了邻接链表转为邻接矩阵初始化邻接矩阵 graph [[] for _ in range(n)]dfs() 的写法 用visi避免重复访问得到每个点所在的联通分量中点的个数
class Solution:def countPairs(self, n: int, edges: List[List[int]]) - int:graph [[] for _ in range(n)]for x, y in edges:graph[x].append(y)graph[y].append(x)visi [False] * ndef dfs(x: int) - int:visi[x] Truecount 1for y in graph[x]:if not visi[y]:count dfs(y)return countres 0for i in range(n):if not visi[i]:count dfs(i)res count * (n - count)return res // 2