拓扑排序

12 篇文章 0 订阅

算法思路:

拓扑排序:
 * 1.找到一个没有后继的顶点
 * 2.从图中删除这个顶点,在列表的前面插入顶点的标记


代码如下:

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/*
 * 拓扑排序:
 * 1.找到一个没有后继的顶点
 * 2.从图中删除这个顶点,在列表的前面插入顶点的标记
 */
public class TopoSort {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		List<Character> vertices = new LinkedList<Character>(Arrays.asList('A', 'B', 'C', 'D', 'E', 
				'F', 'G', 'H'));
		List<LinkedList<Integer>> adjMatrix = new LinkedList<LinkedList<Integer>>();
		adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 1, 1, 0, 0, 0)));
		adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 1, 0, 0, 0)));
		adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 1, 0, 0, 0)));
		adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 1, 0)));
		adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 1, 0)));
		adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 0, 1)));
		adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 0, 1)));
		adjMatrix.add(new LinkedList<Integer>(Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0)));
		
		//topo sort
		char[] sortedArr = new char[vertices.size()];
		while(vertices.size() > 0) {
			int curVertex = noSuccessors(adjMatrix);
			if(curVertex == -1) {
				System.out.println("Graph has cycles");
			} else {
				sortedArr[vertices.size()-1] = vertices.get(curVertex);
				//delete....
				vertices.remove(curVertex);
				adjMatrix.remove(curVertex);
				for(List<Integer> r : adjMatrix) { 
					r.remove(curVertex);
				}
			}
		}
		for(char ch : sortedArr) {
			System.out.print(ch + " ");
		}
		System.out.println();
	}
	
	public static int noSuccessors(List<LinkedList<Integer>> adjMatrix) {
		int curRow = 0;
		boolean isEdge = false;
		for(List<Integer> r : adjMatrix) {
			isEdge = false;
			for(int c : r) {
				if(c == 1) {
					isEdge = true;
					break;
				}
			}
			if(!isEdge) {
				return curRow; 
			}
			curRow++;
		}
		return -1;
	}

}

输出结果是:

C B A E D G F H

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值