注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
请问下大家,这道题,如果有followup要问如何找到所有的path的话,如果用DFS怎么做呢?下面是我的代码:
- class Solution {
- public int[] findOrder(int numCourses, int[][] prerequisites) {
- // use DFS
- // build graph use empty list now
- Map<Integer, List<Integer>> graph = new HashMap<>();
-
- for (int i = 0; i < numCourses; i++) {
- graph.put(i, new ArrayList<>());
- }
-
- for (int[] pair : prerequisites) {
- int first = pair[1];
- int second = pair[0];
- graph.get(first).add(second);
- }
-
- boolean[] visited = new boolean[numCourses];
-
- Deque<Integer> stack = new ArrayDeque<>();
-
- for (int i = 0; i < numCourses; i++) {
- // if we found it has cycle
- if (!visited[i] && hasCycle(graph, i, visited, new HashSet<>(), stack)) {
- return new int[]{};
- }
- }
-
- int[] result = new int[numCourses];
- for (int i = 0; i < numCourses; i++) {
- result[i] = stack.pop();
- }
- return result;
- }
-
- private boolean hasCycle(Map<Integer, List<Integer>> graph, int current, boolean[] visited, Set<Integer> visiting, Deque<Integer> stack) {
- if (visiting.contains(current)) {
- return true;
- }
-
- visiting.add(current);
- //====================================
-
- for (Integer nextClass : graph.get(current)) {
- // if has cycle, return true here!!!!!
- if (!visited[nextClass] && hasCycle(graph, nextClass, visited, visiting, stack)) {
- return true;
- }
- }
-
- //====================================
- visiting.remove(current);
- visited[current] = true;
- stack.push(current);
- return false;
- }
- }
复制代码
|