-
Notifications
You must be signed in to change notification settings - Fork 540
Expand file tree
/
Copy pathbfs.java
More file actions
70 lines (59 loc) · 2.42 KB
/
bfs.java
File metadata and controls
70 lines (59 loc) · 2.42 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
import java.util.*;
import java.io.*;
public class bfs {
private static final int INF = 1000000000;
private static ArrayList<Integer> p = new ArrayList<>();
private static void printPath(int u) {
if (p.get(u) == -1) { System.out.printf("%d", u); return; }
printPath(p.get(u));
System.out.printf(" %d", u);
}
public static void main(String[] args) throws Exception {
/*
// Graph in Figure 4.3, format: list of unweighted edges
// This example shows another form of reading graph input
13 16
0 1 1 2 2 3 0 4 1 5 2 6 3 7 5 6
4 8 8 9 5 10 6 11 7 12 9 10 10 11 11 12
*/
Scanner sc = new Scanner(new File("bfs_in.txt"));
int V = sc.nextInt(), E = sc.nextInt();
ArrayList<ArrayList<IntegerPair>> AL = new ArrayList<>();
for (int u = 0; u < V; ++u) {
ArrayList<IntegerPair> Neighbor = new ArrayList<>();
AL.add(Neighbor);
}
while (E-- > 0) {
int a = sc.nextInt(), b = sc.nextInt();
AL.get(a).add(new IntegerPair(b, 0));
AL.get(b).add(new IntegerPair(a, 0));
}
// as an example, we start from this source, see Figure 4.3
int s = 5;
// BFS routine inside void main(String[] args) -- we do not use recursion
ArrayList<Integer> dist = new ArrayList<>(Collections.nCopies(V, INF)); dist.set(s, 0); // INF = 1e9 here
Queue<Integer> q = new LinkedList<>(); q.offer(s);
p.clear(); p.addAll(Collections.nCopies(V, -1)); // p is global
int layer = -1; // for output printing
Boolean isBipartite = true; // additional feature
while (!q.isEmpty()) {
int u = q.poll();
if (dist.get(u) != layer) System.out.printf("\nLayer %d: ", dist.get(u));
layer = dist.get(u);
System.out.printf("visit %d, ", u);
for (IntegerPair v_w : AL.get(u)) {
int v = v_w.first(); // w ignored
if (dist.get(v) == INF) {
dist.set(v, dist.get(u)+1); // dist[v] != INF now
p.set(v, u); // parent of v is u
q.offer(v); // for next iteration
}
else if ((dist.get(v)%2) == (dist.get(u)%2)) // same parity
isBipartite = false;
}
}
System.out.printf("\nShortest path: ");
printPath(7); System.out.printf("\n");
System.out.printf("isBipartite? %d\n", isBipartite ? 1 : 0);
}
}