活跃农民
- 积分
- 847
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-3-16
- 最后登录
- 1970-1-1
|
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
- // 1.DFS(HashMap to store graph)
- public boolean canFinish(int numCourses, int[][] prerequisites) {
- if(prerequisites == null || prerequisites.length == 0) return true;
-
- // Construct graph
- HashMap<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
- for(int i = 0; i < prerequisites.length; i++){
- int from = prerequisites[i][1];
- int to = prerequisites[i][0];
-
- if(!map.containsKey(from)){
- map.put(from, new ArrayList<Integer>());
- }
-
- List<Integer> list = map.get(from);
- list.add(to);
- map.put(from, list);
- }
-
- // detect cycle one by one using DFS: not visited && has cycle
- int[] visited = new int[numCourses];
- for(int from = 0; from < numCourses; from++){
- if(visited[from] == 0 && hasCycle(from, visited, map)){
- return false;
- }
- }
- return true;
- }
-
- private boolean hasCycle(int from, int[] visited, HashMap<Integer, List<Integer>> map){
- if(visited[from] == 1) return true; //from has already visited
- visited[from] = 1;
-
- // means from is several other courses' prerequisite
- if(map.containsKey(from)){
- for(Integer to : map.get(from)){
- if(visited[to] == 1) return true; //to has already visited
- if(hasCycle(to, visited, map)) return true; //to is in cycle
- }
- }
-
- visited[from] = -1; // finish visit
- return false;
- }
复制代码- // 2.DFS(Using Matrix to store Graph)
- public boolean canFinish(int numCourses, int[][] prerequisites) {
- if(prerequisites == null || prerequisites.length == 0) return true;
-
- // construct graph
- int[][] graph = new int[numCourses][numCourses];
- for(int i = 0; i < prerequisites.length; i++){
- int from = prerequisites[i][1];
- int to = prerequisites[i][0];
- graph[from][to] = 1;
- }
-
- // detect cycle recursive
- int[] visited = new int[numCourses];
- for(int from = 0; from < numCourses; from++){
- if(visited[from] == 0 && hasCycle(from, graph, visited)){
- return false; //there is cycle
- }
- }
-
- return true;
- }
-
- private boolean hasCycle(int from, int[][] graph, int[] visited){
- if(visited[from] == 1) return true; //has already visited from, there is cycle
- visited[from] = 1;
-
- for(int to = 0; to < graph[0].length; to++){
- if(graph[from][to] == 1){
- if(visited[to] == 1) return true; //has already visited
- if(hasCycle(to, graph, visited)) return true;
- }
- }
-
- visited[from] = -1; //finish visited
- return false;
- }
复制代码 这题我用两种方式构建有向图,用HashMap构建可以AC,用Matrix构建就会TLE。大家知道为什么吗?
原题: https://leetcode.com/problems/course-schedule/
|
上一篇: Valid Anagram 编码问题下一篇: CC150+Leetcode刷题实时记录-欢迎加入
|