-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFSExample.java
More file actions
66 lines (54 loc) · 1.53 KB
/
DFSExample.java
File metadata and controls
66 lines (54 loc) · 1.53 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
package example.RecursionExample;
import java.util.ArrayList;
import java.util.List;
/**
* Depth First Search (DFS) + Recursion 範例
*
* Reference:
* - https://www.techiedelight.com/depth-first-search/
*
*/
public class DFSExample {
public static void main(String[] args) {
List<Edge> n = new ArrayList<>();
n.add(new Edge(1, 10));
n.add(new Edge(2, 13));
n.add(new Edge(15, 24));
n.add(new Edge(6, 28));
n.forEach(s -> {
System.out.println("Source: " + s.getSource() + "; Destination: " + s.getDest());
});
for (int i=0; i<n.size(); i++) {
System.out.println("Source: " + n.get(i).getSource() + "; Destination: " + n.get(i).getDest());
}
}
}
class Edge {
public int source, dest;
public Edge(int source, int dest) {
this.source = source;
this.dest = dest;
}
public int getSource() {
return this.source;
}
public int getDest() {
return this.dest;
}
}
class Graph {
List<List<Integer>> adjList = null;
Graph(List<Edge> edges, int n) {
adjList = new ArrayList<>();
for (int i=0; i<n; i++) {
adjList.add(new ArrayList<>());
}
// add edges to the undirected graph
for (Edge edge: edges) {
int src = edge.source;
int dest = edge.dest;
adjList.get(src).add(dest);
adjList.get(dest).add(src);
}
}
}