Skip to content

Commit e934ee1

Browse files
committed
add solution of problem 207: course schedule
1 parent 31641be commit e934ee1

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

CourseSchedule207/README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
There are a total of *n* courses you have to take, labeled from `0` to `n - 1`.
2+
3+
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]`
4+
5+
Given the total number of courses and a list of prerequisite **pairs**, is it possible for you to finish all courses?
6+
7+
For example:
8+
```
9+
2, [[1,0]]
10+
```
11+
There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.
12+
```
13+
2, [[1,0],[0,1]]
14+
```
15+
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.
16+
17+
#####Note:
18+
The input prerequisites is a graph represented by **a list of edges**, not adjacency matrices. Read more about how a graph is represented.

CourseSchedule207/Solution.java

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
public class Solution {
2+
public boolean canFinish(int numCourses, int[][] prerequisites) {
3+
if (prerequisites == null || prerequisites.length <= 1)
4+
return true;
5+
6+
for (int i = 0; i < prerequisites.length; i++) {
7+
for (int j = 0; j < prerequisites.length; j++) {
8+
if (prerequisites[i][1] == prerequisites[j][0]) {
9+
prerequisites[i][1] = prerequisites[j][1];
10+
}
11+
12+
if (prerequisites[i][0] == prerequisites[i][1])
13+
return false;
14+
}
15+
}
16+
17+
return true;
18+
}
19+
}

0 commit comments

Comments
 (0)