在有向图邻接表的基础上,利用队列,可以轻松实现。
ANode:
public class ANode { private int data; private ANode next ; //in-degree private int in; public int getData() { return data; } public void setData(int data) { this.data = data; } public ANode getNext() { return next; } public void setNext(ANode next) { this.next = next; } public int getIn() { return in; } public void setIn(int in) { this.in = in; } }
AGraph:
public class AGraph { private ANode[] headNode; private int n; private int e; public ANode[] getHeadNode() { return headNode; } public void setHeadNode(ANode[] headNode) { this.headNode = headNode; } public int getN() { return n; } public void setN(int n) { this.n = n; } public int getE() { return e; } public void setE(int e) { this.e = e; } }
创建图,输出图,拓扑排序
Interface:
public interface GraphBasicService { public void CreateAgraph(AGraph G, int A[][], int pNum); public void DispAGraph(AGraph g); public void TopologySort(AGraph g); }
class:
public class GraphBasicServiceImpl implements GraphBasicService { /** *create a graph of adjacency list */ public void CreateAgraph(AGraph G, int A[][], int pNum) { ANode p,pre = null; G.setN(pNum); G.setE(0); ANode[] arr = G.getHeadNode(); for(int i = 0; i < G.getN(); i++) { arr[i].setData(i); G.setHeadNode(arr); } for(int i = 0; i < G.getN(); i++) for(int j = 0; j < G.getN(); j++) if(A[i][j] != 0) { p = new ANode(); p.setData(j); arr[j].setIn(arr[j].getIn()+1); if(null == arr[i].getNext()) arr[i].setNext(p); else pre.setNext(p); pre = p; G.setE(G.getE()+1); } } /** *output the graph */ public void DispAGraph(AGraph g) { int i; ANode p; ANode[] arr = g.getHeadNode(); for(i = 0; i < g.getN(); i++) { p =arr[i]; while(p != null) { System.out.print(p.getData()+ "->"); p = p.getNext(); } System.out.println(); } } /** * topology sort,by graph of adjacency list */ public void TopologySort(AGraph g) { int VERTEX_NUM = g.getN(); ANode[] arr = g.getHeadNode(); //this array is the record of topology sort Boolean[] visit = new Boolean[VERTEX_NUM]; for(int i = 0; i < VERTEX_NUM; i++) visit[i] = false; Queue<ANode> queue = new LinkedList<ANode>(); //get the nodes which's in-degree is 0 and add them to the queue for(int i = 0; i < VERTEX_NUM; i++) if(0 == arr[i].getIn()) { visit[i] = true; queue.add(arr[i]); } while(!queue.isEmpty()) { ANode temp = queue.peek(); if(null != temp.getNext()) temp = temp.getNext(); while(null != temp) { //in-degree decremented by one ANode nextNode = arr[temp.getData()]; nextNode.setIn(nextNode.getIn() - 1); temp = nextNode.getNext(); } //get out of the queue and print the data System.out.print(queue.poll().getData() + " "); //add the nodes which's in-degree is 0 and haven't been sorted to the queue for(int i = 0; i < VERTEX_NUM; i++) if(0 == arr[i].getIn() && false == visit[i]) { visit[i] = true; queue.add(arr[i]); } } } }