-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.java
More file actions
64 lines (49 loc) · 1.3 KB
/
DFS.java
File metadata and controls
64 lines (49 loc) · 1.3 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
package com.mycompany.algorithm_final_project;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
/**
*
* @author israkkayumchowdhury
*/
public class DFS {
private final int N = (int) (1e5 + 10);
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>(N);
boolean[] vis = new boolean[N];
public void dfs(int v) {
System.out.println(v + " ");
vis[v] = true;
Iterator<Integer> i = adj.get(v).listIterator();
while (i.hasNext()) {
int n = i.next();
System.out.println("vertex " + v + ", child " + n);
if (vis[n]) {
continue;
}
dfs(n);
}
}
public void dfs_graph() {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
for (int i = 0; i < N; ++i) {
adj.add(new ArrayList<Integer>());
}
// add edge
for (int i = 0; i < m; i++) {
int x, y;
x = s.nextInt();
y = s.nextInt();
adj.get(x).add(y);
adj.get(y).add(x);
}
// dfs
for (int i = 1; i <= n; i++) {
if (vis[i]) {
continue;
}
dfs(i);
}
}
}