题目:找出无向图汇总的相连要素



找出无向图汇总的相连要素  查看运行结果   



18% 
通过

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

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

您在真实的面试中是否遇到过这个题? 

Yes





样例 

给定图:
A------B  C
\     |  | 
  \    |  |
   \   |  |
    \  |  |
      D   E


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


/**
* 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
     List<List<Integer>> resList = new ArrayList<List<Integer>>();
          Queue<UndirectedGraphNode> quene = new LinkedList<UndirectedGraphNode>();
          List<UndirectedGraphNode> visited = new ArrayList<>();
          for (UndirectedGraphNode node : nodes) {
               if (!visited.contains(node)) {
                    List<Integer> path = new ArrayList<Integer>();
                    path.clear();
                    visited.add(node);
                    for (quene.offer(node); !quene.isEmpty(); quene.poll()) {
                         UndirectedGraphNode tmpnode = quene.peek();
                         path.add(tmpnode.label);
                         for (UndirectedGraphNode nn : tmpnode.neighbors) {
                              if (!visited.contains(nn)) {
                                   visited.add(nn);
                                   quene.offer(nn);
                              }
                         }
                    }
                    Collections.sort(path);
                    resList.add(path);

               }

          }
          return resList;
                
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值