blob: 66dd33a87a1cf5329c0c27e297fc5d3b989e2aa7 [file] [log] [blame]
tom144de692014-08-29 11:38:44 -07001package org.onlab.graph;
2
3import java.util.HashSet;
4import java.util.Set;
5
6/**
7 * Implementation of the BFS algorithm.
8 */
9public class BreadthFirstSearch<V extends Vertex, E extends Edge<V>>
10 extends AbstractGraphPathSearch<V, E> {
11
12 @Override
13 public Result<V, E> search(Graph<V, E> graph, V src, V dst, EdgeWeight<V, E> ew) {
14 checkArguments(graph, src, dst);
15
16 // Prepare the graph result.
17 DefaultResult result = new DefaultResult(src, dst);
18
19 // Setup the starting frontier with the source as the sole vertex.
20 Set<V> frontier = new HashSet<>();
21 result.costs.put(src, 0.0);
22 frontier.add(src);
23
24 search: while (!frontier.isEmpty()) {
25 // Prepare the next frontier.
26 Set<V> next = new HashSet<>();
27
28 // Visit all vertexes in the current frontier.
29 for (V vertex : frontier) {
30 double cost = result.cost(vertex);
31
32 // Visit all egress edges of the current frontier vertex.
33 for (E edge : graph.getEdgesFrom(vertex)) {
34 V nextVertex = edge.dst();
35 if (!result.hasCost(nextVertex)) {
36 // If this vertex has not been visited yet, update it.
37 result.updateVertex(nextVertex, edge,
38 cost + (ew == null ? 1.0 : ew.weight(edge)),
39 true);
40 // If we have reached our intended destination, bail.
41 if (nextVertex.equals(dst))
42 break search;
43 next.add(nextVertex);
44 }
45 }
46 }
47
48 // Promote the next frontier.
49 frontier = next;
50 }
51
52 // Finally, but the paths on the search result and return.
53 result.buildPaths();
54 return result;
55 }
56
57}