-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphAlgorithms.java
More file actions
74 lines (70 loc) · 1.79 KB
/
Copy pathGraphAlgorithms.java
File metadata and controls
74 lines (70 loc) · 1.79 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
package kth.csc.inda;
/**
* An example implementation of depth first search.
*
* @author Stefan Nilsson
* @version 2012-12-30
*/
public class GraphAlgorithms {
/**
* Builds an undirected graph and prints the components to stdout.
*
* @param args
* not used
*/
public static void main(String[] args) {
int size = 8;
Graph g = new MatrixGraph(size);
g.addBi(0, 1); //
g.addBi(2, 2); // 0---1 2---
g.addBi(0, 3); // | | | |
g.addBi(1, 4); // 3---4 ----
g.addBi(3, 4); // |
g.addBi(5, 3); // 5 6---7
g.addBi(6, 7); //
System.out.printf("A graph: %s%n", g);
System.out.printf("%n%s%n", "Its components:");
printComponents(g);
}
/**
* Prints the components of g to stdout. Each component is written on a
* separate line.
*/
private static void printComponents(Graph g) {
VertexAction printVertex = new VertexAction() {
@Override
public void act(Graph g, int v) {
System.out.print(v + " ");
}
};
int n = g.numVertices();
boolean[] visited = new boolean[n];
for (int v = 0; v < n; v++) {
if (!visited[v]) {
dfs(g, v, visited, printVertex);
System.out.println();
}
}
}
/**
* Traverses the nodes of g that have not yet been visited. The nodes are
* visited in depth-first order starting at v. The act() method in the
* VertexAction object is called once for each node.
*
* @param g
* an undirected graph
* @param v
* start vertex
* @param visited
* visited[i] is true if node i has been visited
*/
private static void dfs(Graph g, int v, boolean[] visited,
VertexAction action) {
if (visited[v])
return;
visited[v] = true;
action.act(g, v);
for (VertexIterator it = g.neighbors(v); it.hasNext();)
dfs(g, it.next(), visited, action);
}
}