|
| 1 | +package fr.lip6.move.gal.graph; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.HashSet; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Set; |
| 7 | +import java.util.Stack; |
| 8 | + |
| 9 | +import android.util.SparseIntArray; |
| 10 | +import fr.lip6.move.gal.util.IntMatrixCol; |
| 11 | + |
| 12 | +public class Kosaraju { |
| 13 | + |
| 14 | +public static List<List<Integer>> searchForSCC(IntMatrixCol graph) { |
| 15 | +// This part implements Kosaraju to find SCC |
| 16 | +// not the best time complexity algo for that, but enough for us. |
| 17 | +Stack<Integer> stack = new Stack<>(); |
| 18 | +Set<Integer> visited = new HashSet<>(); |
| 19 | + |
| 20 | +// derecursed version uses a todo stack |
| 21 | +Stack<Integer> todo = new Stack<>(); |
| 22 | +for (int p = 0; p < graph.getColumnCount(); p++) { |
| 23 | +todo.add(p); |
| 24 | +} |
| 25 | +while (!todo.isEmpty()) { |
| 26 | +int p = todo.pop(); |
| 27 | +if (p == -1) { |
| 28 | +stack.push(todo.pop()); |
| 29 | +continue; |
| 30 | +} |
| 31 | +SparseIntArray col = graph.getColumn(p); |
| 32 | +if (col.size() > 0) { |
| 33 | +if (!visited.add(p)) { |
| 34 | +continue; |
| 35 | +} |
| 36 | +todo.push(p); |
| 37 | +todo.push(-1); |
| 38 | +for (int i = 0; i < col.size(); i++) { |
| 39 | +todo.push(col.keyAt(i)); |
| 40 | +} |
| 41 | +} |
| 42 | +} |
| 43 | + |
| 44 | +List<List<Integer>> sccs = new ArrayList<>(); |
| 45 | +List<Integer> curScc = new ArrayList<>(); |
| 46 | +visited.clear(); |
| 47 | +graph = graph.transpose(); |
| 48 | +while (!stack.isEmpty()) { |
| 49 | +int cur = stack.pop(); |
| 50 | +visitNode(graph, curScc, cur, visited); |
| 51 | +if (!curScc.isEmpty()) { |
| 52 | +sccs.add(curScc); |
| 53 | +curScc = new ArrayList<>(); |
| 54 | +} |
| 55 | +} |
| 56 | +return sccs; |
| 57 | +} |
| 58 | + |
| 59 | +private static void visitNode(IntMatrixCol graph, List<Integer> curScc, int cur, Set<Integer> visited) { |
| 60 | +if (visited.add(cur)) { |
| 61 | +curScc.add(cur); |
| 62 | +SparseIntArray col = graph.getColumn(cur); |
| 63 | +for (int i = 0; i < col.size(); i++) { |
| 64 | +visitNode(graph, curScc, col.keyAt(i), visited); |
| 65 | +} |
| 66 | +} |
| 67 | +} |
| 68 | + |
| 69 | +} |
0 commit comments