Breadth First Search or BFS for a Graph - Java Data Structure

Java examples for Data Structure:Graph

Description

Breadth First Search or BFS for a Graph

Demo Code

package com.company.algs.graph.bfs;

import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

@SuppressWarnings({ "Duplicates", "WeakerAccess" })
public class BFS {
    public Vertex search(Vertex start, String searchName) {
        LinkedList<Vertex> queue = new LinkedList<>();
        queue.addLast(start);/*from w w w .  j a v a2 s .  c  om*/

        while (!queue.isEmpty()) {
            Vertex vertex = queue.pollFirst();
            vertex.color = Vertex.Color.BLACK;

            if (vertex.name.equals(searchName)) {
                return vertex;
            }

            for (Vertex v : vertex.adjacentVertices) {
                if (v.color == Vertex.Color.WHITE) {
                    v.color = Vertex.Color.GREY;
                    v.depth = vertex.depth + 1;
                    queue.addLast(v);
                }
            }
        }
        return null;
    }

    /**
     * Test main method
     */
    public static void main(String[] args) {
        Vertex vertexA = new Vertex("A");
        Vertex vertexB = new Vertex("B");
        Vertex vertexC = new Vertex("C");
        Vertex vertexD = new Vertex("D");
        Vertex vertexE = new Vertex("E");
        Vertex vertexF = new Vertex("F");
        Vertex vertexG = new Vertex("G");

        vertexA.adjacentVertices = Arrays.asList(vertexB, vertexC);
        vertexB.adjacentVertices = Arrays.asList(vertexA, vertexD);
        vertexC.adjacentVertices = Arrays.asList(vertexA, vertexE);
        vertexD.adjacentVertices = Arrays.asList(vertexB, vertexE);
        vertexE.adjacentVertices = Arrays.asList(vertexC, vertexF, vertexD);
        vertexF.adjacentVertices = Arrays.asList(vertexE, vertexG);
        vertexG.adjacentVertices = Collections.singletonList(vertexF);

        BFS bfs = new BFS();
        Vertex vertex = bfs.search(vertexG, "A");
        System.out.println(vertex == null ? "Not found" : vertex);
    }

    private static class Vertex {
        private List<Vertex> adjacentVertices;
        private String name;
        private int depth;
        private Color color;

        Vertex(String name) {
            this.name = name;
            color = Color.WHITE;
        }

        @Override
        public String toString() {
            return "Vertex{" + "name='" + name + '\'' + ", depth=" + depth
                    + ", color=" + color + '}';
        }

        private enum Color {
            BLACK, GREY, WHITE
        }
    }
}

Related Tutorials