Number of Connected Components in an Undirected Graph
犯的错:1.没有check n和edges的合法性,2 按照树的bfs来写了,遇到互不相连的图时,无法完成全部遍历,应该把while循环卸载所有node遍历的for里面
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Example 1:
Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]
0 3
| |
1 --- 2 4
Output: 2Example 2:
Input: n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]]
0 4
| |
1 --- 2 --- 3
Output: 1Note:
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
BFS
由于每个节点仅被发现一次,因此每个节点入栈和出栈各一次,时间均为O(1),故入栈和出栈总时间为O(V);由于需要对每个节点的邻接表进行扫描,时间为O(Adj[u]),总时间为O(E);综上所示,广度优先搜索的时间复杂度为O(V+E).即是图邻接表大小的线性函数
犯的错: while 循环里的for循环,应该循环poll出来的数对应的set,笔误写成了最外层for循环的i了,当就一个node,和谁都不连时,应该返回n
Last updated