首页 > 代码库 > 图论算法(6)(更新版) --- Tarjan算法求强连通分量

图论算法(6)(更新版) --- Tarjan算法求强连通分量

之前Tarjan算法求强连通分量博文中,代码实现用到了固定大小数组,扩展起来似乎并不是很方便,在java里这样来实现本身就是不太妥当的,所以下面给出一个更新版本的代码实现:

package test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

public class TarjanSCC<NodeType> {
	int index;
	Map<NodeType, LinkedList<NodeType>> dag;
	Map<NodeType, Integer> indexMap;
	Map<NodeType, Integer> lowLinkMap;
	Stack<NodeType> stack;
	List<List<NodeType>> result;

	public TarjanSCC(Map<NodeType, LinkedList<NodeType>> dag) {
		this.index = 0;
		this.dag = dag;
		this.indexMap = new HashMap<NodeType, Integer>();
		this.lowLinkMap = new HashMap<NodeType, Integer>();
		this.result = new ArrayList<List<NodeType>>();
	}

	public List<List<NodeType>> tarjan() {
		this.index = 0;
		stack = new Stack<NodeType>();
		List<List<NodeType>> result = new ArrayList<List<NodeType>>();
		for (NodeType v : this.dag.keySet()) {
			if (indexMap.get(v) == null) {
				result.addAll(this.strongConnect(v));
			}
		}
		return result;
	}

	public List<NodeType> getSuccessors(NodeType v,Map<NodeType, LinkedList<NodeType>> dag) {
		List<NodeType> successors = new ArrayList<NodeType>();
		Set<NodeType> set = dag.keySet();
		Iterator<NodeType> it = set.iterator();
		while (it.hasNext()) {
			NodeType node = it.next();
			if (node.equals(v)) {
				successors.addAll(dag.get(node));
				break;
			}
		}
		return successors;
	}

	public List<List<NodeType>> strongConnect(NodeType v) {
		indexMap.put(v, index);
		lowLinkMap.put(v, index);
		index++;
		stack.push(v);
		for (NodeType w : getSuccessors(v, dag)) {
			if (indexMap.get(w) == null) {
				strongConnect(w);
				lowLinkMap.put(v, Math.min(lowLinkMap.get(v), lowLinkMap.get(w)));
			} else if (stack.contains(w)) {
				lowLinkMap.put(v, Math.min(lowLinkMap.get(v), indexMap.get(w)));
			}
		}
		if (lowLinkMap.get(v).equals(indexMap.get(v))) {
			List<NodeType> sccList = new ArrayList<NodeType>();
			while (true) {
				NodeType w = stack.pop();
				sccList.add(w);
				if (w.equals(v)) {
					break;
				}
			}
			if (sccList.size() > 1) {
				result.add(sccList);
			}
		}
		return result;
	}
}




图论算法(6)(更新版) --- Tarjan算法求强连通分量