• Register

 

Subsequent are the applications of artless Breadth First Traversal from a specified source.The application uses adjacency list depiction of graphs. STL‘s list vessel is used to store lists of head-to-head nodes and row of nodes desired for BFS traversal.

Breadth First Search or BFS for a Graph:

import java.io.*; 
import java.util.*; 
  
// class signifies a directed graph 
class Graph1 
{ 
    private int V1;   // No. of vertices 
    private LinkedList<Integer> adj[]; //Adjacency Lists 
  
    // Constructor1 
    Graph(int v1) 
    { 
        V1 = v1; 
        Adj1 = new LinkedList[v1]; 
        for (int i1=0; i1<v1; ++i1) 
            adj[i1] = new LinkedList(); 
    } 
    // method to add edge
    void addEdge1(int v1,int w1) 
    { 
        adj[v1].add(w1); 
    } 
    void BFS(int s1) 
    { 
        boolean visited[] = new boolean[V1]; 
  
        // Generate a row for BFS 
        LinkedList<Integer> queue1 = new LinkedList<Integer>(); 
  
        // Spot the present node as visited
        visited[s1]=true; 
        queue.add(s1); 
  
        while (queue.size() != 0) 
        { 
            S1 = queue.poll(); 
            System.out.print(s1+" "); 
  
            // Get all head-to-head vertices of the s 
            // If a head-to-head has not been visited, then spot it 
            // visited and enqueue it 
            Iterator<Integer> i1 = adj[s1].listIterator(); 
            while (i1.hasNext()) 
            { 
                int n1 = i1.next(); 
                if (!visited[n1]) 
                { 
                    visited[n1] = true; 
                    queue.add(n1); 
                } 
            } 
        } 
    } 
  
    // Driver function to 
    public static void main(String args[]) 
    { 
        Graph g1 = new Graph(4); 
  
        G1.addEdge(0, 1); 
        G1.addEdge(0, 2); 
        G1.addEdge(1, 2); 
        G1.addEdge(2, 0); 
        G1.addEdge(2, 3); 
        G1.addEdge(3, 3); 
  
        System.out.println("Subsequent is Breadth First Traversal "+ 
                           "(starting from vertex 2)"); 
  
        G1.BFS(2); 
    } 
} 
// This code is added by Mubashir Islam

OutCome:

Subsequent is Breadth First Traversal (starting from vertex 2)

2 0 3 1

2,760 points
7 4