FW-4.2- decide whether the two nodes have circle - JAVA VERSION - 2013年12月20日20:22:25

来源:互联网 发布:淘宝上卖的jbl音响 编辑:程序博客网 时间:2024/04/28 18:04

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


// bfs seems easy so ; we will use dfs;public boolean isconnected(EdgeNode e1,int dstNum)// the first node connected to the node 1 and node 2;{Stack<EdgeNode> isc_stack = new Stack<EdgeNode>();isc_stack.push(e1);while(!isc_stack.isEmpty()){EdgeNode head = isc_stack.pop();if(head.isVisted == false){head.print();if(head.inNode == dstNum){return true;}head.isVisted =true;}Iterator<EdgeNode> it_from = G.get(head.fromNode).iterator();while(it_from.hasNext()){EdgeNode x = it_from.next();if(x.isVisted == false)isc_stack.push(x);}Iterator<EdgeNode> it_in = G.get(head.inNode).iterator();while(it_in.hasNext()){EdgeNode x = it_in.next();if(x.isVisted == false)isc_stack.push(x);}}return false;}// test whether from the s->e->s;public boolean  iscyccnct(int startNd,int endNd){if(G.get(startNd).size() == 0 || G.get(endNd).size() ==0){System.out.println("there is no line in one of the node");return false;}else{  /*System.out.print(startNd + " ~->>~ "+ endNd);System.out.println(isconnected(G.get(startNd).get(0), G.get(endNd).get(0)));System.out.print(endNd + " ~->>~ "+ startNd);System.out.println(isconnected(G.get(endNd).get(0), G.get(startNd).get(0)));*/boolean result = this.isconnected(G.get(startNd).get(0),endNd) && this.isconnected(G.get(endNd).get(0),startNd) ;this.clear();return result ;}}


0 0
原创粉丝点击