您的位置:首页 > Web前端 > Node.js

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

2013-12-21 09:24 302 查看
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 ;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐