1. 程式人生 > >lintcode431- Connected Component in Undirected Graph- medium

lintcode431- Connected Component in Undirected Graph- medium

-- amp dir res directed connect 開始 for notice

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.)

Notice

Each connected component should sort by label.

Example

Given graph:

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

Return {A,B,D}, {C,E}. Since there are two connected component which is {A,B,D}, {C,E}

public List<List<Integer>> connectedSet(List<UndirectedGraphNode> nodes)

算法:for循環每個點,如果沒被訪問過,就開始做BFS產生新的List,加到List<List>裏面。BFS做的內容就是最簡單的加label,遍歷鄰居。

數據結構:Queue+Set標配 (這題set兩個地方用到,一個是主函數for循環檢查要去BFS不,一個是子函數BFS裏查要加進queue不),。

細節:給List排序的函數是Collections.sort(list);

/**
 * 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(List<UndirectedGraphNode> nodes) { // write your code here List<List<Integer>> result = new ArrayList<List<Integer>>(); if (nodes == null || nodes.size() == 0) { return result; } Set<UndirectedGraphNode> globalSet = new HashSet<UndirectedGraphNode>(); for (UndirectedGraphNode node : nodes) { if (globalSet.contains(node)) { continue; } List<Integer> list = bfs(node, globalSet); result.add(list); } return result; } private List<Integer> bfs(UndirectedGraphNode node, Set<UndirectedGraphNode> globalSet) { List<Integer> result = new ArrayList<Integer>(); Queue<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>(); // 其實冗余了,不需要再來個局部的set,用全局的就夠了,因為某一個點被加進去過了就不可能存在在另一個團裏被加第二次了。 // Set<UndirectedGraphNode> set = new HashSet<UndirectedGraphNode>(); queue.offer(node); globalSet.add(node); while (!queue.isEmpty()) { UndirectedGraphNode crt = queue.poll(); result.add(crt.label); for (UndirectedGraphNode neighbor : crt.neighbors) { if (!globalSet.contains(neighbor)) { queue.offer(neighbor); globalSet.add(neighbor); } } } Collections.sort(result); return result; } }

lintcode431- Connected Component in Undirected Graph- medium