查看: 1652| 回复: 0
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] Course Schedule II 如何用DFS找出所有path

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
请问下大家,这道题,如果有followup要问如何找到所有的path的话,如果用DFS怎么做呢?下面是我的代码:
  1. class Solution {
  2.     public int[] findOrder(int numCourses, int[][] prerequisites) {
  3.         // use DFS
  4.         // build graph use empty list now
  5.         Map<Integer, List<Integer>> graph = new HashMap<>();
  6.         
  7.         for (int i = 0; i < numCourses; i++) {
  8.             graph.put(i, new ArrayList<>());
  9.         }
  10.         
  11.         for (int[] pair : prerequisites) {
  12.             int first = pair[1];
  13.             int second = pair[0];
  14.             graph.get(first).add(second);
  15.         }
  16.         
  17.         boolean[] visited = new boolean[numCourses];
  18.         
  19.         Deque<Integer> stack = new ArrayDeque<>();
  20.         
  21.         for (int i = 0; i < numCourses; i++) {
  22.             // if we found it has cycle
  23.             if (!visited[i] && hasCycle(graph, i, visited, new HashSet<>(), stack)) {
  24.                 return new int[]{};
  25.             }
  26.         }
  27.         
  28.         int[] result = new int[numCourses];
  29.         for (int i = 0; i < numCourses; i++) {
  30.             result[i] = stack.pop();
  31.         }
  32.         return result;
  33.     }
  34.    
  35.     private boolean hasCycle(Map<Integer, List<Integer>> graph, int current, boolean[] visited, Set<Integer> visiting, Deque<Integer> stack) {
  36.         if (visiting.contains(current)) {
  37.             return true;
  38.         }
  39.         
  40.         visiting.add(current);
  41.         //====================================
  42.         
  43.         for (Integer nextClass : graph.get(current)) {
  44.             // if has cycle, return true here!!!!!
  45.             if (!visited[nextClass] && hasCycle(graph, nextClass, visited, visiting, stack)) {
  46.                 return true;
  47.             }
  48.         }
  49.             
  50.         //====================================
  51.         visiting.remove(current);
  52.         visited[current] = true;
  53.         stack.push(current);
  54.         return false;
  55.     }
  56. }
复制代码



上一篇:今年amazon oa可以用python么?
下一篇:请教一道MS的OA题目
您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表