首页 > 其他 > 详细

CC150 4.2

时间:2014-11-27 08:02:23      阅读:326      评论:0      收藏:0      [点我收藏+]

4.2 Given a directed graph, design an algorithm to find out whether there is a route between two nodes.

Node
{
  List<Node> neighbours;
}

boolean isConnected(Node from, Node to)
{
  Stack<Node> toVisit = initStack();
  Set<Node> seen = initSet();
  
  toVisit.push(from);
  
  while (!toVisit.isEmpty())
  {
    Node n = toVisit.pop();
    
    if (n == to)
      return true;
    
    while (Node neighbour : n.neighbours)
    {
      if (!seen.contains(neighbour))
      {
        seen.add(neighbour);
        toVisit.add(neighbour);
      }    
    }
  }
  
  return false;  
}


CC150 4.2

原文:http://7371901.blog.51cto.com/7361901/1583040

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!