001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.algorithms;
003
004import java.util.ArrayDeque;
005import java.util.ArrayList;
006import java.util.Collection;
007import java.util.Collections;
008import java.util.Deque;
009import java.util.HashMap;
010import java.util.List;
011import java.util.Map;
012
013import org.openstreetmap.josm.data.osm.Node;
014import org.openstreetmap.josm.data.osm.NodeGraph;
015import org.openstreetmap.josm.tools.Pair;
016import org.openstreetmap.josm.tools.Utils;
017
018/**
019 * Tarjan's strongly connected components algorithm for JOSM.
020 *
021 * @author gaben
022 * @see <a href="https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm">
023 * Tarjan's strongly connected components algorithm</a>
024 * @since 19062
025 */
026public final class Tarjan {
027
028    /**
029     * Used to remember visited nodes and its metadata. Key is used for storing
030     * the unique ID of the nodes instead of the full data to save space.
031     */
032    private final Map<Long, TarjanHelper> registry;
033
034    /** Used to store the graph data as a map. */
035    private final Map<Node, List<Node>> graphMap;
036
037    /** Used to store strongly connected components. NOTE: single nodes are not stored to save memory. */
038    private final Collection<List<Node>> scc = new ArrayList<>();
039
040    /** Used on algorithm runtime to keep track discovery progress. */
041    private final Deque<Node> stack = new ArrayDeque<>();
042
043    /** Used on algorithm runtime to keep track discovery progress. */
044    private int index;
045
046    /**
047     * Initialize the Tarjan's algorithm.
048     *
049     * @param graph graph data in NodeGraph object format
050     */
051    public Tarjan(NodeGraph graph) {
052        graphMap = graph.createMap();
053
054        this.registry = new HashMap<>(Utils.hashMapInitialCapacity(graph.getEdges().size()));
055    }
056
057    /**
058     * Returns the strongly connected components in the current graph. Single nodes are ignored to save memory.
059     *
060     * @return the strongly connected components in the current graph
061     */
062    public Collection<List<Node>> getSCC() {
063        for (Node node : graphMap.keySet()) {
064            if (!registry.containsKey(node.getUniqueId())) {
065                strongConnect(node);
066            }
067        }
068        return scc;
069    }
070
071    /**
072     * Returns the graph data as a map.
073     *
074     * @return the graph data as a map
075     * @see NodeGraph#createMap()
076     */
077    public Map<Node, List<Node>> getGraphMap() {
078        return graphMap;
079    }
080
081    /**
082     * Calculates strongly connected components available from the given node, in an iterative fashion.
083     *
084     * @param u0 the node to generate strongly connected components from
085     */
086    private void strongConnect(final Node u0) {
087        final Deque<Pair<Node, Integer>> work = new ArrayDeque<>();
088        work.push(new Pair<>(u0, 0));
089        boolean recurse;
090
091        while (!work.isEmpty()) {
092            Pair<Node, Integer> popped = work.remove();
093            Node u = popped.a;
094            int j = popped.b;
095
096            if (j == 0) {
097                index++;
098                registry.put(u.getUniqueId(), new TarjanHelper(index));
099                stack.push(u);
100            }
101
102            recurse = false;
103            List<Node> successors = getSuccessors(u);
104
105            for (int i = j; i < successors.size(); i++) {
106                Node v = successors.get(i);
107                if (!registry.containsKey(v.getUniqueId())) {
108                    work.push(new Pair<>(u, i + 1));
109                    work.push(new Pair<>(v, 0));
110                    recurse = true;
111                    break;
112                } else if (stack.contains(v)) {
113                    TarjanHelper uHelper = registry.get(u.getUniqueId());
114                    TarjanHelper vHelper = registry.get(v.getUniqueId());
115                    uHelper.lowlink = Math.min(uHelper.lowlink, vHelper.index);
116                }
117            }
118
119            if (!recurse) {
120                TarjanHelper uHelper = registry.get(u.getUniqueId());
121                if (uHelper.lowlink == uHelper.index) {
122                    List<Node> currentSCC = new ArrayList<>();
123                    Node v;
124                    do {
125                        v = stack.remove();
126                        currentSCC.add(v);
127                    } while (!v.equals(u));
128
129                    // store the component only if it makes a cycle, otherwise it's a waste of memory
130                    if (currentSCC.size() > 1) {
131                        scc.add(currentSCC);
132                    }
133                }
134                if (!work.isEmpty()) {
135                    Node v = u;
136                    Pair<Node, Integer> peeked = work.peek();
137                    u = peeked.a;
138                    TarjanHelper vHelper = registry.get(v.getUniqueId());
139                    uHelper = registry.get(u.getUniqueId());
140                    uHelper.lowlink = Math.min(uHelper.lowlink, vHelper.lowlink);
141                }
142            }
143        }
144    }
145
146    /**
147     * Returns the next direct successors from the graph of the given node.
148     *
149     * @param node a node to start search from
150     * @return direct successors of the node or an empty list, if it's a terminal node
151     */
152    private List<Node> getSuccessors(Node node) {
153        return graphMap.getOrDefault(node, Collections.emptyList());
154    }
155
156    /**
157     * Helper class for storing the Tarjan algorithm runtime metadata.
158     */
159    private static final class TarjanHelper {
160        private final int index;
161        private int lowlink;
162
163        private TarjanHelper(int index) {
164            this.index = index;
165            this.lowlink = index;
166        }
167    }
168}