tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame^] | 1 | package org.onlab.graph; |
| 2 | |
| 3 | import java.util.HashSet; |
| 4 | import java.util.Set; |
| 5 | |
| 6 | /** |
| 7 | * Implementation of the BFS algorithm. |
| 8 | */ |
| 9 | public 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 | } |