Breadth-first search in Java


In graph theory, breadth-first search (BFS) is a strategy for searching in a graph when search is limited to essentially two operations:

  1. Visit and inspect a node of a graph;
  2. Gain access to visit the nodes that neighbor the currently visited node. The BFS begins at a root node and inspects all the neighboring nodes.

Find more here.

This is simple java implementation of Breadth-first search.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package myclass.Graphs;

import myclass.PrintArray;

/**
 *
 * @author wijebandara
 */
public class BreadthFirstSearch
{
    private int [][] data;
    private int [] d;
    private int [] pi;
    private int [] state;

    BreadthFirstSearch(int data[][])
    {
        this.data = new int[data.length][data.length];
        this.data=data;
        this.d=new int[data.length];
        this.pi=new int[data.length];
        this.state=new int [data.length];

    }
    public void breadthFirstSearch(int s)
    {

        java.util.LinkedList<Integer>  q=new java.util.LinkedList<Integer>();
        for(int i=0;i<data.length;i++)
        {
            state[i]=-1;
            d[i]=0;
        }
        q.add(s);
        state[s]=0;

        while(q.size()!=0)
        {
            int hold= q.removeFirst();

            for(int i=0;i<data.length;i++)
            {
                if(data[hold][i]!=0 && state[i]==-1)
                {
                    q.add(i);
                    state[i]=0;
                    d[i]=d[hold]+1;
                    pi[i]=hold;
                }
            }
            state[hold]=1;
        }
        PrintArray.printArray(d," ");
    }
    public boolean isPathBetween(int u,int v)
    {
        breadthFirstSearch(u);
        if(d[v]!=0)
        {
            return true;
        }
        return false;
    }

}

Hope you will enjoy…!

Leave a comment