# LeetCode 207 Course Schedule

given a 2D array, represents for the class and it’s prerequesite class
like [0,1], it means that we should take class 1 before class 0.

so it is a problem about cycle detection.

public boolean canFinish(int numCourses, int[][] prerequisites)


return if it is possible for us to finish all the courses.

idea:
just test if there exist any cycle in starting from each node, if there is, then we can’t iterate every class, but if there isn’t, then we can.

class Solution {
public boolean canFinish(int numCourses, int[][] prerequisites) {
HashMap<Integer, List<Integer>> map = new HashMap<>();

for (int[] class_pre: prerequisites) {
if (map.containsKey(class_pre[1])) {
} else {
map.put(class_pre[1], new ArrayList<>());
}
}
boolean[] visited = new boolean[numCourses];
for (int i = 0; i < numCourses; i++) {
if (isCycle(i, map, visited)) {
return false;
}
}
return true; //if there is no cycle in this graph, then we can finish all the courses
}

private boolean isCycle(int currentNode, HashMap<Integer, List<Integer>> map, boolean[] visited) {
if (visited[currentNode]) {
return true;
}
if (!map.containsKey(currentNode)) {
return false;//it actually means that we reached onee path's end
}

visited[currentNode] = true;
boolean res = false;
for (Integer neighbor: map.get(currentNode)) {
res = isCycle(neighbor, map, visited);
if (res) {
break;
}
}
//if any of the res is true, then it is true
visited[currentNode] = false;
return res;
}
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

Tech In Pieces

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

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

08-10 5950
03-03 2653

05-30 1484
03-19 268
03-17 823
03-20 1万+
03-17 50
05-20 5123
06-02 392
09-28
06-06