查找一个有向网络的头节点和尾节点

原文地址:https://download.csdn.net/blog/column/12554187/136269346

4
0 1 0 2 1 2 2 3
输出:0 3

2
0 1 0 2
输出:0 1 2

2
0 1 1 0
输出:-1

3
0 1 0 2 2 0
输出:-1

解题思路

这个题考察基础的dfs遍历, 重点在解决环的问题,需要用一个集合存储自己访问的路径,如果下一个访问的点已经存在路径中,说明这是一个环,直接退出递归循环

public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()) {
			int num =sc.nextInt();
			Map<Integer,List<Integer>> map = new HashMap<Integer,List<Integer>>();
			Integer head = null;
			for(int i=0; i< num;i++) {
				Integer key = sc.nextInt();
				map.computeIfAbsent(key, k->new ArrayList<Integer>()).add(sc.nextInt());
				if(map.size() ==1) { // 第一个点就是头节点
					head = key;
				}
			}
			Set<Integer> tailNodeList = new TreeSet<Integer>();//具有排序功能保存结果
			boolean isOk = solution(map, head, new HashMap<Integer,Integer>(), tailNodeList);
			if(!isOk) {
				System.out.println(-1);
			}else {
				System.out.print(head);
				tailNodeList.stream().forEach(abc->System.out.print(" "+abc));
			}
		}
	}
	public static boolean solution(Map<Integer,List<Integer>> map, Integer head, 
			Map<Integer,Integer> hisVisMap, Set<Integer> tailNodeList){
		if(hisVisMap.get(head) != null) {
			return false; // 访问的这个节点已经出现在历史访问中,说明出现了环
		}
		hisVisMap.put(head, 1);// 标记已经访问
		List<Integer> children = map.get(head);
		if(children == null || children.size() ==0) {//没有子映射是尾巴
			tailNodeList.add(head);//叶子节点放入结果集中
		}else {
			for(Integer key : children) {
				if(!solution(map, key, hisVisMap, tailNodeList)) {
					return false; //如果任何一次出现环,则直接返回
				}
			}
		}
		hisVisMap.remove(head); // 恢复
		return true;
	}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值