拓扑排序是判断有向图是否有环的基础算法
这是节点的bean
public class Node {
public String name; //节点名字
public Integer indegree; //入度个数
public List<Node> child=new ArrayList<Node>();//所指向的几点
@Override
public String toString() {
return "Node [name=" + name + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getIndegree() {
return indegree;
}
public void setIndegree(Integer indegree) {
this.indegree = indegree;
}
public List<Node> getChild() {
return child;
}
public void setChild(List<Node> child) {
this.child = child;
}
public Node(String name) {
this.name = name;
}
public Node(){}
}
拓扑排序的核心
public static void topSort(List<Node> vs) {
Queue<Node> q = new LinkedList<Node>();
int size=vs.size();
int count = 0;
//初始化队列
for (Node n : vs) {
if (n.indegree == 0)
q.add(n);
}
//将入度为0的节点输出 并且将其所指向的节点的入度值-1
while (!q.isEmpty()) {
Node v = q.poll();
count++;
for (Node w : v.getChild()) {
if (--w.indegree == 0)
q.add(w);
}
}
//计算节点的个数和 最后出队列的个数 若不一样则有环
if (count !=size) {
System.out.println(" 图有圈");
}
}
因为每次要set属性很麻烦所以写了一个邻接矩阵转化为list的代码
public static List<Node> ArrayToGraph(int[][] a) throws NullPointerException{
//判断是否为矩阵
//Y 继续 N 返回NULL
for(int i=0;i<a.length;i++){
if(a[i].length!=a.length){
return null;
}
}
//建立list 泛型为节点
List<Node> list=new ArrayList<Node>();
//建立map key为 节点的编号 value 为 节点的所指向的节点的编号
@SuppressWarnings("rawtypes")
Map<Integer,ArrayList> map=new HashMap<Integer,ArrayList>();
// 对map 赋值
//建立入度数组
int[] indegree=new int[a.length+1];
//计算每个节点的入度值
for(int i=0;i<a.length;i++){
for(int j=0;j<a.length;j++)
{
indegree[i]=a[j][i]+indegree[i];
}
}
for(int i=0;i<a.length;i++){
Node v1 = new Node("v"+i);
//为每一个node节点的indegree 属性赋值
v1.indegree=indegree[i];
list.add(v1);
ArrayList<Integer> li=new ArrayList<Integer>();
for(int j=0;j<a[i].length;j++){
if(a[i][j]==1)
li.add(j);
}
map.put(i, li);
}
// 为每一个node节点的child 属性加入 对应的Node
for(Entry<Integer, ArrayList> m:map.entrySet()){
Node n= list.get(m.getKey());
ArrayList<Integer> l=m.getValue();
for(Integer i:l){
n.child.add(list.get(i));
}
}
return list;
}
测试
public static void main(String[] args) {
int a[][]={{0,1,1,1,0,0,0},
{0,0,0,1,1,0,0},
{0,0,0,0,0,1,0},
{0,0,1,0,0,1,1},
{0,0,0,1,0,0,1},
{0,0,0,0,0,0,0},
{0,0,0,0,0,1,0}
};
List<Node> list=Vertex.ArrayToGraph(a);
try{Vertex.topSort(list);}
catch(NullPointerException e){
System.out.println("请输入矩阵");
}
}
算法的思想很多 大家可以百度 这里主要是怎么实现
初次写博客,请大家见谅(而且我还很懒)