lintcode:Find the Connected Component in the Undirected Graph 找出无向图汇总的相连要素

时间:2024-04-12 10:05:00

题目:

请找出无向图中相连要素的个数。

图中的每个节点包含其邻居的 1 个标签和 1 个列表。(一个无向图的相连节点(或节点)是一个子图,其中任意两个顶点通过路径相连,且不与超级图中的其它顶点相连。)

样例

给定图:

A------B  C
\ | |
\ | |
\ | |
\ | |
D E

返回 {A,B,D}, {C,E}。其中有 2 个相连的元素,即{A,B,D}, {C,E}

解题:

广度优先+递归,写不出来,程序来源

Java程序:

/**
* Definition for Undirected graph.
* class UndirectedGraphNode {
* int label;
* ArrayList<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
* };
*/
public class Solution {
/**
* @param nodes a array of Undirected graph node
* @return a connected set of a Undirected graph
*/
public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) {
// Write your code here int m = nodes.size();
Map<UndirectedGraphNode, Boolean> visited = new HashMap<>(); for (UndirectedGraphNode node : nodes){
visited.put(node, false);
} List<List<Integer>> result = new ArrayList<>(); for (UndirectedGraphNode node : nodes){
if (visited.get(node) == false){
bfs(node, visited, result);
}
} return result;
} public void bfs(UndirectedGraphNode node, Map<UndirectedGraphNode, Boolean> visited, List<List<Integer>> result){ List<Integer>row = new ArrayList<>(); Queue<UndirectedGraphNode> queue = new LinkedList<>();
visited.put(node, true);
queue.offer(node); while (!queue.isEmpty()){
UndirectedGraphNode u = queue.poll();
row.add(u.label); for (UndirectedGraphNode v : u.neighbors){
if (visited.get(v) == false){
visited.put(v, true);
queue.offer(v);
}
}
} Collections.sort(row);
result.add(row); }
}

总耗时: 7732 ms

Python程序: