01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package algs42;
import stdlib.*;
/* ***********************************************************************
 *  Compilation:  javac TransitiveClosure.java
 *  Execution:    java TransitiveClosure filename.txt
 *  Dependencies: Digraph.java DepthFirstDirectedPaths.java In.java StdOut.java
 *  Data files:   http://algs4.cs.princeton.edu/42directed/tinyDG.txt
 *
 *  Compute transitive closure of a digraph and support
 *  reachability queries.
 *
 *  Preprocessing time: O(V(E + V)) time.
 *  Query time: O(1).
 *  Space: O(V^2).
 *
 *  % java TransitiveClosure tinyDG.txt
 *         0  1  2  3  4  5  6  7  8  9 10 11 12
 *  --------------------------------------------
 *    0:   T  T  T  T  T  T
 *    1:      T
 *    2:   T  T  T  T  T  T
 *    3:   T  T  T  T  T  T
 *    4:   T  T  T  T  T  T
 *    5:   T  T  T  T  T  T
 *    6:   T  T  T  T  T  T  T        T  T  T  T
 *    7:   T  T  T  T  T  T  T  T  T  T  T  T  T
 *    8:   T  T  T  T  T  T  T  T  T  T  T  T  T
 *    9:   T  T  T  T  T  T           T  T  T  T
 *   10:   T  T  T  T  T  T           T  T  T  T
 *   11:   T  T  T  T  T  T           T  T  T  T
 *   12:   T  T  T  T  T  T           T  T  T  T
 *
 *************************************************************************/

public class TransitiveClosure {
  private final DirectedDFS[] tc;  // tc[v] = reachable from v

  public TransitiveClosure(Digraph G) {
    tc = new DirectedDFS[G.V()];
    for (int v = 0; v < G.V(); v++)
      tc[v] = new DirectedDFS(G, v);
  }

  public boolean reachable(int v, int w) {
    return tc[v].marked(w);
  }

  // test client
  public static void main(String[] args) {
    args = new String[] { "data/tinyDG.txt" };

    In in = new In(args[0]);
    Digraph G = new Digraph(in);

    TransitiveClosure tc = new TransitiveClosure(G);

    // print header
    StdOut.print("     ");
    for (int v = 0; v < G.V(); v++)
      StdOut.format("%3d", v);
    StdOut.println();
    StdOut.println("--------------------------------------------");

    // print transitive closure
    for (int v = 0; v < G.V(); v++) {
      StdOut.format("%3d: ", v);
      for (int w = 0; w < G.V(); w++) {
        if (tc.reachable(v, w)) StdOut.format("  T");
        else                    StdOut.format("   ");
      }
      StdOut.println();
    }
  }

}