forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraph.java
More file actions
49 lines (36 loc) · 1.04 KB
/
Copy pathGraph.java
File metadata and controls
49 lines (36 loc) · 1.04 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
package modern.challenge;
import java.util.Iterator;
import java.util.LinkedList;
public class Graph {
private final int v;
private final LinkedList<Integer>[] adjacents;
@SuppressWarnings("unchecked")
public Graph(int v) {
this.v = v;
adjacents = new LinkedList[v];
for (int i = 0; i < v; ++i) {
adjacents[i] = new LinkedList();
}
}
void addEdge(int v, int e) {
adjacents[v].add(e);
}
void BFS(int start) {
boolean visited[] = new boolean[v];
LinkedList<Integer> queue = new LinkedList<>();
visited[start] = true;
queue.add(start);
while (!queue.isEmpty()) {
start = queue.poll();
System.out.print(start + " ");
Iterator<Integer> i = adjacents[start].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}
}