-
Notifications
You must be signed in to change notification settings - Fork 109
Expand file tree
/
Copy pathBFS.java
More file actions
98 lines (76 loc) · 2.58 KB
/
BFS.java
File metadata and controls
98 lines (76 loc) · 2.58 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package com.graphX.graphX;
import com.graphX.graphX.helper.Pair;
import com.graphX.graphX.helper.Triple;
import java.util.*;
public class BFS {
List<Integer> minDistanceFromSource;
List<Boolean> visited;
Graph graph;
int n;
public BFS(Graph graph) {
this.graph = graph;
this.n = graph.n;
}
public void clear() {
minDistanceFromSource = new ArrayList<>(Collections.nCopies(n, -1));
visited = new ArrayList<>(Collections.nCopies(n, false));
}
public void run(int sourceR) {
int source = graph.h.hash(sourceR);
bfs(source);
}
public void run(Pair<Integer, Integer> sourceR) {
int source = graph.h.hash(sourceR);
bfs(source);
}
public void run(Triple<Integer, Integer, Integer> sourceR) {
int source = graph.h.hash(sourceR);
bfs(source);
}
public int minDistance(int targetR) {
int target = graph.h.hash(targetR);
return minDistInternal(target);
}
public int minDistance(Pair<Integer, Integer> targetR) {
int target = graph.h.hash(targetR);
return minDistInternal(target);
}
public int minDistance(Triple<Integer, Integer, Integer> targetR) {
int target = graph.h.hash(targetR);
return minDistInternal(target);
}
public boolean isVisited(int source) {
return isVisitedInternal(source);
}
public boolean isVisited(Pair<Integer, Integer> sourceR) {
int source = graph.h.hash(sourceR);
return isVisitedInternal(source);
}
public boolean isVisited(Triple<Integer, Integer, Integer> sourceR) {
int source = graph.h.hash(sourceR);
return isVisitedInternal(source);
}
private void bfs(int source) {
Queue<Integer> queue = new LinkedList<>();
queue.add(source);
minDistanceFromSource.set(source, 0);
while (!queue.isEmpty()) {
int current = queue.peek();
for (int i = 0; i < graph.adjacencyList.get(current).size(); i++) {
int adjNode = graph.adjacencyList.get(current).get(i).first;
if (!visited.get(adjNode)) {
visited.set(adjNode, true);
minDistanceFromSource.set(adjNode, minDistanceFromSource.get(current) + 1);
queue.add(adjNode);
}
}
queue.poll();
}
}
private int minDistInternal(int target) {
return minDistanceFromSource.get(target);
}
private boolean isVisitedInternal(int target) {
return visited.get(target);
}
}