查看: 1245| 回复: 1
跳转到指定楼层
上一主题 下一主题
收起左侧

找出无向图汇总的相连要素 求助

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
本帖最后由 jy_121 于 2015-8-24 23:10 编辑

这是lintcode上的一道原题,大意就是把图中相连通的部分放到一个集合里输出:

http://www.lintcode.com/zh-cn/pr ... e-undirected-graph/


我是用了BFS来做,但是其中一个test case里一个集合中的顺序和答案不一样,报错了。但是题目里好像没有这样的要求,不知道是为什么。
代码如下:
  1. public List<List<Integer>> connectedSet(ArrayList<UndirectedGraphNode> nodes) {
  2.         // Write your code here
  3.         List<List<Integer>> result = new ArrayList<List<Integer>> ();
  4.         Queue<UndirectedGraphNode> q = new LinkedList<UndirectedGraphNode>();
  5.         HashMap<UndirectedGraphNode, Integer> map
  6.         = new HashMap<UndirectedGraphNode, Integer>();

  7.         
  8.         for(int i = 0; i < nodes.size(); i++){
  9.                 if(map.containsKey(nodes.get(i))){
  10.                         continue;
  11.                 }
  12.                 ArrayList<Integer> list = new ArrayList<Integer>();
  13.                 q.offer(nodes.get(i));
  14.                 map.put(nodes.get(i), 1);
  15.                 while(!q.isEmpty()){
  16.                         UndirectedGraphNode node2 = q.poll();
  17.                         if(!list.contains(node2.label)){
  18.                                 list.add(node2.label);
  19.                         }
  20.                    
  21.                     for(UndirectedGraphNode n : node2.neighbors){
  22.                             if(!map.containsKey(n)){
  23.                                     q.offer(n);
  24.                                 list.add(n.label);
  25.                                 map.put(n, 1);
  26.                         }
  27.                     }
  28.                    
  29.                 }
  30.                
  31.                 result.add(list);
  32.                
  33.         }
  34.         return result;
  35.         
  36.     }
复制代码
这是报错时的截图,谢谢大家了









question.png (25.02 KB, 下载次数: 0)

question.png

上一篇:求问一个关于time complexity的概念问题
下一篇:请教一道面经
🔗
 楼主| jy_121 2015-8-28 11:24:38 | 只看该作者
全局:
把list排序后就可以通过,估计是题目的要求有些问题。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表