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

本文介绍了一种使用深度优先搜索(DFS)算法来判断有向图中两个节点间是否存在路径的方法。通过栈结构实现递归过程,并利用迭代方式遍历所有可达节点,检查目标节点是否可达。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 ;
			
		}
	
	}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值