拓扑排序实例

在前面的文章《深度优先搜索》中介绍了拓扑排序,在《深度优先实现拓扑排序–java》中给出了一种Java实现,其实现方式是从出度为0的点(也就是它不依赖任何其他点)逆向遍历的。其实还可以正向遍历,过程在前一篇文章的伪代码中给出。这里看两道相关题目加深理解应用。

1.Course Schedule

There are a total of n courses you have to take, labeled from0 ton - 1.

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]

Given the total number of courses and a list of prerequisitepairs, is it possible for you to finish all courses?

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So it is possible.

2, [[1,0],[0,1]]

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.

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more abouthow a graph is represented.

这显然是拓扑排序问题,不过本题只需要判断有无环即可,具体思路可以参考开头给出的文章链接。可以用广度优先搜索,也可以用深度优先搜索。深度优先搜索可以用递归,也可以模拟递归。直接用递归,效率比较低,本题目的话会超时。下面程序中的global数组用于记录元素的全局使用情况。有人可能会想到从所有
入度为0的点开始遍历,或者从出度为0的点逆向遍历,这都能得到正确的解,但是没有必要。

下面给出递归与非递归版本

递归:

public class Solution {
    boolean[] used;
    boolean[] global;
//    LinkedList<Integer> res = new LinkedList<Integer>();
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        ArrayList[] graph = new ArrayList[numCourses];
        for(int[] pre:prerequisites){
            if(graph[pre[0]] == null) graph[pre[0]] = new ArrayList<Integer>();
            graph[pre[0]].add(pre[1]);
        }
        used = new boolean[numCourses];
        global = new boolean[numCourses];
        for(int i = 0;i < numCourses;i++){
            if(global[i]) continue;
            Arrays.fill(used,false);
            if(!dfs(graph,i)) return false;
        }
        return true;
    }
    public boolean dfs(List<Integer>[] graph,int x){
        boolean res = true;
        used[x] = true;
        global[x] = true;
        if(graph[x] == null) return true;
        for(int y:graph[x]){
            if(used[y]) return false;
//          res.addFirst(y);
            res = res & dfs(graph,y);
            used[y] = false;
        }
        return res;
    }
}

非递归版本

public class Solution {
    boolean[] used;
    boolean[] global;
//  LinkedList<Integer> res = new LinkedList<Integer>();
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        ArrayList[] graph = new ArrayList[numCourses];
        for(int[] pre:prerequisites){
            if(graph[pre[0]] == null) graph[pre[0]] = new ArrayList<Integer>();
            graph[pre[0]].add(pre[1]);
        }
        global = new boolean[numCourses];
        used = new boolean[numCourses];
        LinkedList<Integer> stack = new LinkedList<Integer>();
        for(int i = 0;i < numCourses;i++){
            Arrays.fill(used,false);
            if(global[i]) continue;
            stack.addLast(i);
            used[i] = true;
            global[i] = true;
            if(graph[i] == null) {stack.removeLast();used[i] = false;continue;}
            boolean flag = false;
            while(stack.size() > 0){
                int course = stack.getLast();
                if(graph[course] == null){stack.removeLast(); used[course] = false;continue;}
                flag = false;
                Integer index = null;
                for(int j = 0;j < graph[course].size();j++){
                    index = (Integer)(graph[course].get(j));
                    if(used[index]) return false;
                    if(global[index]) continue;
                    global[index] = true;
                    used[index] = true;
                    stack.addLast(index);
                    flag = true;
                    break;
                }
                if(!flag) {index = stack.removeLast();used[index] = false;}
            }
        }
        return true;
    }
}

2.Course Schedule II

There are a total of n courses you have to take, labeled from0 ton - 1.

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]

Given the total number of courses and a list of prerequisitepairs, return the ordering of courses you should take to finish all courses.

There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array.

For example:

2, [[1,0]]

There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is[0,1]

4, [[1,0],[2,0],[3,1],[3,2]]

There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is[0,1,2,3]. Another correct ordering is[0,2,1,3].

Note:
The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more abouthow a graph is represented.

同上题一样,只不过这里要求给出结果。关于这道题由于Java不允许创建泛型数组,所以需要强制转换工作。另外,Java的对象数组创建数组后,相应的对象并未创建,使用数组的时候需要注意先创建对象。

代码如下:

public class Solution {
    public int[] findOrder(int numCourses, int[][] prerequisites) {
        ArrayList[] g = new ArrayList[numCourses];
        for(int[] pre:prerequisites){
            if(g[pre[0]] == null) g[pre[0]] = new ArrayList<Integer>();
            g[pre[0]].add(pre[1]);
        }
        int k = 0;
        int cur = 0;
        int[] res = new int[numCourses];
        if(prerequisites.length == 0 && numCourses > 0){
            for(int i = 0;i < numCourses;i++) res[i] = i;
            return res;
        }
        LinkedList<Integer> stack = new LinkedList<Integer>();
        boolean[] global = new boolean[numCourses];
        for(int i = 0;i < numCourses;i++){
            if(global[i]) continue;
            global[i] = true;
            if(g[i] == null) {res[k++] = i; continue;}
            boolean[] used = new boolean[numCourses];
            stack.addLast(i);
            used[i] = true;
            while(stack.size() > 0){
                int cour = stack.getLast();
                if(g[cour] == null){cur = stack.removeLast(); used[cur] = false; res[k++] = cur; continue;}
                boolean flag = false;
                for(int index = 0;index < g[cour].size();index++){
                    int c = (Integer)(g[cour].get(index));
                    if(used[c]) return new int[0];
                    if(global[c]) continue;
                    used[c] = true;
                    global[c] = true;
                    stack.addLast(c);
                    flag = true;
                    break;
                }
                if(!flag){cur = stack.removeLast(); used[cur] = false; res[k++] = cur;}
            }
        }//
        return res;
    }
}






    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/cumtwyc/article/details/50833254
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞