Connected Component in Undirected Graph
Find the number connected component in the undirected graph. Each node in the graph contains a label and a list of its neighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices are connected to each other by paths, and which is connected to no additional vertices in the supergraph.)
Example
Given graph:
Return {A,B,D}, {C,E}. Since there are two connected component which is {A,B,D}, {C,E}
Solution:
求解决方案的具体个数可以想到DFS, 但是隐式DFS的模式大多都是在循环内把结果添加进入临时的current变量, 但是对于图不是特别适合,主要是图有邻居节点,简单的做法就是在利用isVisited 字典,只访问节点一次,第二添加结果集在DFS循环外。这道题的第二个重点就是,结果返回的label集合,而不是节点集合。
Last updated
Was this helpful?