-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDFS.java
64 lines (52 loc) · 1.55 KB
/
DFS.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
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Stack;
public class DFS {
private static ArrayList<ArrayList<Integer>> graph;
private static boolean[] visited;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
graph = new ArrayList<>();
for (int i = 0; i < n; ++i) {
graph.add(new ArrayList<>());
}
visited = new boolean[n];
while (scanner.hasNext()) {
int u = scanner.nextInt();
int v = scanner.nextInt();
graph.get(u).add(v);
}
scanner.close();
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
dfsWithStack(i);
}
for (boolean isVisited : visited) {
System.out.print(isVisited + " ");
}
System.out.println();
}
}
public static void dfsRecursive(int pos) {
visited[pos] = true;
for (int neighbor : graph.get(pos)) {
if (!visited[neighbor]) {
dfsRecursive(neighbor);
}
}
}
public static void dfsWithStack(int start) {
Stack<Integer> stack = new Stack<>();
stack.add(start);
while (!stack.isEmpty()) {
int pos = stack.pop();
visited[pos] = true;
for (int neighbor : graph.get(pos)) {
if (!visited[neighbor]) {
stack.push(neighbor);
}
}
}
}
}