-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFStransitiveClosure.java
More file actions
76 lines (64 loc) · 2 KB
/
DFStransitiveClosure.java
File metadata and controls
76 lines (64 loc) · 2 KB
1
2
3
4
5
6
7
8
9
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
76
import java.util.ArrayList;
import java.util.Scanner;
public class DFStransitiveClosure {
static class Graph {
private int vertices;
private ArrayList<Integer>[] adjList;
private int[][] tc;
public Graph(int vertices) {
this.vertices = vertices;
this.tc = new int[this.vertices][this.vertices];
initAdjList();
}
// @SuppressWarnings("unchecked")
private void initAdjList() {
adjList = new ArrayList[vertices];
for (int i = 0; i < vertices; i++) {
adjList[i] = new ArrayList<>();
}
}
public void addEdge(int u, int v) {
adjList[u].add(v);
}
public void transitiveClosure() {
for (int i = 0; i < vertices; i++) {
dfsUtil(i, i);
}
}
private void dfsUtil(int s, int v) {
tc[s][v] = 1;
for (int adj : adjList[v]) {
if (tc[s][adj] == 0) {
dfsUtil(s, adj);
}
}
}
public void printTransitiveClosure() {
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
System.out.print(tc[i][j] + " ");
}
}
System.out.println();
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int t = scanner.nextInt();
while (t-- > 0) {
int n = scanner.nextInt();
Graph graph = new Graph(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int val = scanner.nextInt();
if (val == 1) {
graph.addEdge(i, j);
}
}
}
graph.transitiveClosure();
graph.printTransitiveClosure();
}
scanner.close();
}
}