|
| 1 | +class Solution { |
| 2 | + int[] res; |
| 3 | + int resIdx = 0; |
| 4 | + boolean[] visited; |
| 5 | + List<List<Integer>> adjacencyList; |
| 6 | + public int[] findOrder(int numCourses, int[][] prerequisites) { |
| 7 | + res = new int[numCourses]; |
| 8 | + visited = new boolean[numCourses]; |
| 9 | + adjacencyList = createAdjacencyList(numCourses, prerequisites); |
| 10 | + Stack<Integer> visitesInDfs = new Stack<>(); |
| 11 | + for (int i = 0; i < numCourses; i++) { |
| 12 | + if (!dfs(i, visitesInDfs)) { |
| 13 | + int[] tmpRes = {}; |
| 14 | + return tmpRes; |
| 15 | + } |
| 16 | + } |
| 17 | + return res; |
| 18 | + } |
| 19 | + |
| 20 | + |
| 21 | + public boolean dfs(int currCourseNum, Stack<Integer> visitesInDfs) { |
| 22 | + if (visitesInDfs.contains(currCourseNum)) { |
| 23 | + return false; |
| 24 | + } |
| 25 | + if (visited[currCourseNum]) { |
| 26 | + return true; |
| 27 | + } |
| 28 | + visited[currCourseNum] = true; |
| 29 | + visitesInDfs.add(currCourseNum); |
| 30 | + List<Integer> currCourseWithPreq = adjacencyList.get(currCourseNum); |
| 31 | + for (int preq : currCourseWithPreq) { |
| 32 | + if (!dfs(preq, visitesInDfs)) { |
| 33 | + return false; |
| 34 | + } |
| 35 | + } |
| 36 | + res[resIdx++] = currCourseNum; |
| 37 | + visitesInDfs.pop(); |
| 38 | + return true; |
| 39 | + } |
| 40 | + |
| 41 | + public List<List<Integer>> createAdjacencyList(int numCourses, int[][] prerequisites) { |
| 42 | + List<List<Integer>> adjacencyList = new ArrayList<>(); |
| 43 | + for (int i = 0; i < numCourses; i++) { |
| 44 | + adjacencyList.add(new ArrayList<>()); |
| 45 | + } |
| 46 | + |
| 47 | + for (int[] coursePreqArr : prerequisites) { |
| 48 | + List<Integer> coursePreqList = adjacencyList.get(coursePreqArr[0]); |
| 49 | + for (int i = 1; i < coursePreqArr.length; i++) { |
| 50 | + coursePreqList.add(coursePreqArr[i]); |
| 51 | + } |
| 52 | + } |
| 53 | + return adjacencyList; |
| 54 | + } |
| 55 | +} |
0 commit comments