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); |
tom | c53fa0d | 2014-08-29 11:57:11 -0700 | [diff] [blame^] | 15 | |
tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame] | 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); |
tom | c53fa0d | 2014-08-29 11:57:11 -0700 | [diff] [blame^] | 23 | |
| 24 | search: |
| 25 | while (!frontier.isEmpty()) { |
tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame] | 26 | // 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); |
tom | c53fa0d | 2014-08-29 11:57:11 -0700 | [diff] [blame^] | 32 | |
tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame] | 33 | // 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. |
tom | c53fa0d | 2014-08-29 11:57:11 -0700 | [diff] [blame^] | 42 | if (nextVertex.equals(dst)) { |
tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame] | 43 | break search; |
tom | c53fa0d | 2014-08-29 11:57:11 -0700 | [diff] [blame^] | 44 | } |
tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame] | 45 | next.add(nextVertex); |
| 46 | } |
| 47 | } |
| 48 | } |
tom | c53fa0d | 2014-08-29 11:57:11 -0700 | [diff] [blame^] | 49 | |
tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame] | 50 | // Promote the next frontier. |
| 51 | frontier = next; |
| 52 | } |
tom | c53fa0d | 2014-08-29 11:57:11 -0700 | [diff] [blame^] | 53 | |
tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame] | 54 | // Finally, but the paths on the search result and return. |
| 55 | result.buildPaths(); |
| 56 | return result; |
| 57 | } |
tom | c53fa0d | 2014-08-29 11:57:11 -0700 | [diff] [blame^] | 58 | |
tom | 144de69 | 2014-08-29 11:38:44 -0700 | [diff] [blame] | 59 | } |