leetcode 207. Course Schedule (DFS)

There are a total of n courses you have to take, labeled from 0 to n-1.

Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]

Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?

Example 2:

Input: 2, [[1,0],[0,1]]
Output: false
Explanation: There are a total of 2 courses to take.
To take course 1 you should have finished course 0, and to take course 0 you should also have finished course 1. So it is impossible.

题目是给一个图,让判断图中有无闭环。

题中给出的图是edge形式的,给出图的每条边,而首先要把edge形式的图转换成邻接链表形式方便处理。

然后对每个起始点做DFS处理,对每个起始点来说,保存每个经过的点,如果经过的点出现在保存的路径里面,就说明有闭环,返回false,所有的点处理完后没有闭环,就返回true。

同时用一个visited来保存节点是否已经被访问过,如果被访问过就不需要再次访问。
这里visited和图的维度一样

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        ArrayList<ArrayList<Integer>> course = new ArrayList<ArrayList<Integer>>(numCourses);
        ArrayList<ArrayList<Boolean>> visited = new ArrayList<ArrayList<Boolean>>(numCourses);
        HashSet<Integer> hash = new HashSet<>();
        
        for (int i = 0; i < numCourses; i++) {
        	course.add(new ArrayList<Integer>());
        	visited.add(new ArrayList<Boolean>());
        }
        
        for (int i = 0; i < prerequisites.length; i++) {
        	course.get(prerequisites[i][0]).add(prerequisites[i][1]);
        	visited.get(prerequisites[i][0]).add(false);
        }
        
        for (int i = 0; i < course.size(); i++) {
        	if (course.get(i).size() == 0) {
        		continue;
        	}
        	
        	if (!dfs(course, i, hash, visited)) {
        		return false;
        	}
        	
        }
        return true;
    }
	
	public boolean dfs(ArrayList<ArrayList<Integer>> course, int level, 
			HashSet<Integer> hash, ArrayList<ArrayList<Boolean>> visited) {
		
		if (hash.contains(level)) {
			return false;
		}
		hash.add(level);
		
		for (int i = 0; i < course.get(level).size(); i++) {
			if (!visited.get(level).get(i)) {
				visited.get(level).set(i, true);
				if (!dfs(course, course.get(level).get(i), hash, visited)) {
					return false;
				}
			}
		}
		//访问完的点移出路径
		hash.remove(new Integer(level));
		return true;
	}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值