In the previous blog post on the Tarjan Algorithm for strongly connected components, the code implementation uses a fixed-size array, which does not seem convenient to be extended. in Java, this implementation is not appropriate, so the following provides an updated version of code implementation:
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;}}
Graph Algorithm (6) (new version) --- Tarjan Algorithm for strongly connected components