blob: c02afea948de9f6c628762020ffdc32a878a6b0f [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);
tomc53fa0d2014-08-29 11:57:11 -070015
tom144de692014-08-29 11:38:44 -070016 // 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);
tomc53fa0d2014-08-29 11:57:11 -070023
tom19bf4212014-08-29 13:08:29 -070024 boolean reachedEnd = false;
25 while (!reachedEnd && !frontier.isEmpty()) {
tom144de692014-08-29 11:38:44 -070026 // Prepare the next frontier.
27 Set<V> next = new HashSet<>();
28
29 // Visit all vertexes in the current frontier.
30 for (V vertex : frontier) {
31 double cost = result.cost(vertex);
tomc53fa0d2014-08-29 11:57:11 -070032
tom144de692014-08-29 11:38:44 -070033 // Visit all egress edges of the current frontier vertex.
34 for (E edge : graph.getEdgesFrom(vertex)) {
35 V nextVertex = edge.dst();
36 if (!result.hasCost(nextVertex)) {
37 // If this vertex has not been visited yet, update it.
38 result.updateVertex(nextVertex, edge,
39 cost + (ew == null ? 1.0 : ew.weight(edge)),
40 true);
41 // If we have reached our intended destination, bail.
tomc53fa0d2014-08-29 11:57:11 -070042 if (nextVertex.equals(dst)) {
tom19bf4212014-08-29 13:08:29 -070043 reachedEnd = true;
44 break;
tomc53fa0d2014-08-29 11:57:11 -070045 }
tom144de692014-08-29 11:38:44 -070046 next.add(nextVertex);
47 }
tom19bf4212014-08-29 13:08:29 -070048
49 if (reachedEnd) {
50 break;
51 }
tom144de692014-08-29 11:38:44 -070052 }
53 }
tomc53fa0d2014-08-29 11:57:11 -070054
tom144de692014-08-29 11:38:44 -070055 // Promote the next frontier.
56 frontier = next;
57 }
tomc53fa0d2014-08-29 11:57:11 -070058
tom144de692014-08-29 11:38:44 -070059 // Finally, but the paths on the search result and return.
60 result.buildPaths();
61 return result;
62 }
tomc53fa0d2014-08-29 11:57:11 -070063
tom144de692014-08-29 11:38:44 -070064}