码迷,mamicode.com
首页 > 编程语言 > 详细

JAVA邻接表实现拓扑排序

时间:2015-11-22 00:17:02      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

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

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
 * 
 * */

 

  技术分享技术分享

技术分享

 

JAVA邻接表实现拓扑排序

标签:

原文地址:http://www.cnblogs.com/liyinggang/p/4984972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!