数据结构与算法之拓扑排序Java实现

什么是拓扑排序呢?
此处省略一万字,下面主要讲怎么实现,


实现拓扑排序要抓住几点

  1. 统计入度为0的节点(可以用队列实现)
  2. 每一个节点的出度包括哪些节点(Map+List)
  3. 每个节点的入度为多少(数组)

例子+具体实现
题目来源:Leetcode 207
题目如下:There are a total of n courses you have to take, labeled from 0 to n - 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 prerequisite pairs, 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 about how a graph is represented.
You may assume that there are no duplicate edges in the input prerequisites.

Java代码如下:

class Solution {
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        if(numCourses<=1||prerequisites==null||prerequisites.length==0) return true;
        int[] courses=new int[numCourses];//存储节点的入度
        Map> hash=new HashMap>();
        for(int i=0;iint[] temp=prerequisites[i];
            courses[temp[0]]++;
            if(hash.containsKey(temp[1])){
                hash.get(temp[1]).add(temp[0]);
            }else{
                List list=new ArrayList();
                list.add(temp[0]);
                hash.put(temp[1],list);
            }
        }
        Queue queue=new LinkedList<>();
        for(int i=0;iif(courses[i]==0)
                queue.add(i);
        }
        while(!queue.isEmpty()){
            int c=queue.poll();
            List temp=hash.get(c);
            if(temp==null) continue;
            for(int i=0;iget(i)]--;
                if(courses[temp.get(i)]==0)
                    queue.add(temp.get(i));
            }
        }
        for(int i=0;iif(courses[i]!=0)
                return false;
        return true;
    }
}

你可能感兴趣的:(数据结构之拓扑排序Java,拓扑排序,Leetcode,算法)