[Random Coding]Topological Sorting



package random;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import util.*;

public class TopologicalSort {

	// DFS
	public static List<GraphNode> topological(HashSet<GraphNode> set) {
		List<GraphNode> result = new ArrayList<GraphNode>();
		Hashtable<GraphNode, String> table = new Hashtable<GraphNode, String>();
		Iterator<GraphNode> it = set.iterator();
		while(it.hasNext()){
			GraphNode temp = it.next();
			table.put(temp, "white");
		}
		it = set.iterator();
		GraphNode cur = null;
		while (it.hasNext()) {
			cur = it.next();
			if(table.get(cur) == "white")
				visit(result, table, cur);
		}
		return result;
	}

	public static void visit(List<GraphNode> result,
			Hashtable<GraphNode, String> table, GraphNode source) {
		if(table.get(source) == "grey")
			return;
		if(table.get(source) == "white"){
			table.put(source, "grey");
			if(source.edge != null){
				List<GraphNode> list = source.edge;
				for(int i = 0; i < list.size(); i++)
					visit(result, table, list.get(i));
			}
			table.put(source, "black");
			result.add(0, source);
		}
	}
	
	public static void main(String[] args){
		GraphNode v1 = new GraphNode();
		v1.value = 1;
		GraphNode v2 = new GraphNode();
		v2.value = 2;
		GraphNode v3 = new GraphNode();
		v3.value = 3;
		GraphNode v4 = new GraphNode();
		v4.value = 4;
		GraphNode v5 = new GraphNode();
		v5.value = 5;
		List<GraphNode> list1 = new ArrayList<GraphNode>();
		list1.add(v2);
		list1.add(v4);
		v1.edge = list1;
		List<GraphNode> list3 = new ArrayList<GraphNode>();
		list3.add(v1);
		list3.add(v5);
		v3.edge = list3;
		List<GraphNode> list2 = new ArrayList<GraphNode>();
		list2.add(v4);
		v2.edge = list2;
		HashSet<GraphNode> set = new HashSet<GraphNode>();
		set.add(v1);
		set.add(v2);
		set.add(v3);
		set.add(v4);
		set.add(v5);
		List<GraphNode> result = topological(set);
		for(int i = 0; i < result.size(); i++)
			System.out.println(result.get(i).value);
	}
}

package util;

import java.util.List;

public class GraphNode {
	public int value;
	public List<GraphNode> edge;
	public GraphNode(){
		
	}
	public GraphNode(int value, List<GraphNode> list){
		this.value = value;
		this.edge = list;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值