JAVA邻接矩阵实现拓扑排序

由于一直不适用邻接表 ,现在先贴一段使用邻接矩阵实现图的拓扑排序以及判断有无回路的问题。自己做的图。将就看吧。

package TopSort;

import java.util.LinkedList;
import java.util.Scanner;

/*拓扑序列:对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性
 * 序列,使得图中任意一对顶点u和v,若<u,v> ∈E(G),则u在线性序列中出现在v之前。
 * 
 */

public class TopSort {
	
	static int[][] map;
	static int[] indegree; // 这n个点的入度
	static int n, m; //顶点数,边数
	static LinkedList<Integer> stack = new LinkedList<Integer>(); //模拟栈

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		m = sc.nextInt();
		map = new int[n][n];
		indegree = new int[n];
		for (int i = 0; i < n; i++) {
			indegree[i] = 0;
			for (int j = 0; j < n; j++) {
				map[i][j] = 0;
			}
		}
		int x, y;
		for (int i = 0; i < m; i++) {
			x = sc.nextInt();
			y = sc.nextInt();
			if (map[x][y] == 0) { // 判重边
				map[x][y] = 1;
				indegree[y]++;
			}

		}
		topSort1();  
		topSort2();
	}
	//遍历顺序一:广度遍历
	private static void topSort1() {
		int count = 0; //判断有无回路(是否成环)
		for (int i = 0; i < n; i++) {
			if (indegree[i] == 0) {
				stack.addFirst(i);
				indegree[i] = -1;
			}
		}
		while (!stack.isEmpty()) {
			int p = stack.removeFirst();
			System.out.print(p + " ");
			count++;
			for (int j = 0; j < n; j++) {
				if (map[p][j] == 1) {
					map[p][j] = 0;
					indegree[j]--;
					if (indegree[j] == 0) {
						stack.addFirst(j);
						indegree[j] = -1;
					}
				}
			}
		}
		System.out.println();
		if(count <n) System.out.println("The network has a cycle!"); //当输出的顶点数小于图中的顶点数时,输出有回路信息
		else  System.out.println("The network has not a cycle!");
	}
	//遍历顺序二:深度遍历
	private static void topSort2() {
		int count = 0; //判断有无回路(是否成环)
		for (int i = 0; i < n; i++) {
			if (indegree[i] == 0) {
				stack.addFirst(i);
				indegree[i] = -1;
			}
			while (!stack.isEmpty()) {
				int p = stack.removeFirst();
				System.out.print(p+" ");
				count ++;
				for (int j = 0; j < n; j++) {
					if (map[p][j] == 1) {
						map[p][j] = 0;
						indegree[j]--;
						if (indegree[j] == 0) {
							stack.addFirst(j);
							indegree[j] = -1;
						}
					}
				}
			}
		}
		System.out.println();
		if(count <n) System.out.println("The network has a cycle!"); //当输出的顶点数小于图中的顶点数时,输出有回路信息
		else  System.out.println("The network has not a cycle!");
	}

}
/*
 * 7 8
 * 
 * 0 1
 * 0 3
 * 1 2
 * 1 6
 * 3 6
 * 4 3
 * 4 5
 * 5 6
 * 
 * */

 

  

 

posted @ 2015-11-21 22:38  樱花庄的龙之介大人  阅读(1189)  评论(0编辑  收藏  举报