-
Notifications
You must be signed in to change notification settings - Fork 0
/
Graph.java
91 lines (81 loc) · 2.54 KB
/
Graph.java
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import java.util.*;
class Graph {
static int timer = 0;
static class Vertex implements Comparable<Vertex> {
int postOrder, val;
boolean visited, marked;
List<Vertex> adj, adj1; // adj: reverse graph adjacency List, adj1: main graph adjacency list
public Vertex(int v) {
adj = new ArrayList<>();
adj1 = new ArrayList<>();
visited = false;
marked = false;
this.val = v;
}
public void add(Vertex v) {
adj.add(v);
v.adj1.add(this);
}
public List<Vertex> explore() {
List<Vertex> scc = new ArrayList<>();
scc.add(this);
this.marked = true;
for (Vertex v: adj1) {
if (!v.marked) {
List<Vertex> subScc = v.explore();
scc.addAll(subScc);
}
}
return scc;
}
public void dfs() {
visited = true;
++(Graph.timer);
for (Vertex v: adj) {
if (!v.visited) {
v.dfs();
}
}
postOrder = ++(Graph.timer);
//System.out.println(this + " -> " + postOrder);
}
public int compareTo(Vertex v) {
return v.postOrder - postOrder;
}
public String toString() {
return "" + this.val;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nodes = sc.nextInt();
Vertex[] vertices = new Vertex[nodes+1];
for (int i=1; i<=nodes; i++) {
vertices[i] = new Vertex(i);
}
int edges = sc.nextInt();
for(int i=0; i<edges; i++) {
int u = sc.nextInt(), v = sc.nextInt();
vertices[v].add(vertices[u]);
}
for (int i=1; i<=nodes; i++) {
if (!vertices[i].visited) {
vertices[i].dfs();
}
}
Arrays.sort(vertices, 1, nodes+1);
int scc = 0;
for (int i=1; i<=nodes; i++) {
if (!vertices[i].marked) {
System.out.println(vertices[i].val + " :) " + vertices[i].postOrder);
List<Vertex> newScc = vertices[i].explore();
scc++;
System.out.print("SCC no: " + scc + " => ");
for (Vertex v: newScc) {
System.out.print(v + " ");
}
System.out.println();
}
}
}
}