All Downloads are FREE. Search and download functionalities are using the official Maven repository.

gr.james.simplegraph.examples.BreadthFirstSearch Maven / Gradle / Ivy

Go to download

Simple Graph is a graph interface for Java 6 that is designed to expose a very simple API to support working with graphs

The newest version!
package gr.james.simplegraph.examples;

import gr.james.simplegraph.DirectedGraph;

import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Set;

/**
 * Demonstration of breadth first search (BFS) using a queue.
 */
public final class BreadthFirstSearch {
    private BreadthFirstSearch() {
    }

    /**
     * Performs BFS on a directed graph.
     * 

* Complexity: O(V+E) * * @param g the graph * @param source the source vertex * @return the number of vertices that are reachable from {@code source} (self included) * @throws NullPointerException if {@code g} is {@code null} * @throws IndexOutOfBoundsException if {@code source} is not in the graph */ public static int breadthFirstSearch(DirectedGraph g, int source) { final Deque queue = new LinkedList(); final Set visited = new HashSet(); queue.offer(source); visited.add(source); while (!queue.isEmpty()) { final int next = queue.poll(); for (int adj : g.adjacentOut(next)) { if (visited.add(adj)) { queue.offer(adj); } } } return visited.size(); } }





© 2015 - 2025 Weber Informatics LLC | Privacy Policy