java邻接表_JAVA邻接表实现拓扑排序

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

package TopSort;

import java.util.LinkedList;

import java.util.Scanner;

/*拓扑序列:对一个有向无环图(Directed Acyclic Graph简称DAG)G进行拓扑排序,是将G中所有顶点排成一个线性

* 序列,使得图中任意一对顶点u和v,若 ∈E(G),则u在线性序列中出现在v之前。

*

*/

public class TopSort {

static int[][] map;

static int[] indegree; // 这n个点的入度

static int n, m; //顶点数,边数

static LinkedList stack = new LinkedList(); //模拟栈

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

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

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

*

* */

20180110172610536173.png

20180110172610549844.png

20180110172610563515.png

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值