The Wayback Machine - https://web.archive.org/web/20240816172532/https://www.geeksforgeeks.org/bfs-disconnected-graph/
Open In App

BFS for Disconnected Graph

Last Updated : 14 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In the previous post, BFS only with a particular vertex is performed i.e. it is assumed that all vertices are reachable from the starting vertex. But in the case of a disconnected graph or any vertex that is unreachable from all vertex, the previous implementation will not give the desired output, so in this post, a modification is done in BFS. 

Dis1

 All vertices are reachable. So, for the above graph, simple BFS will work. 

Di2

 As in the above graph vertex 1 is unreachable from all vertex, so simple BFS wouldn’t work for it.

Just to modify BFS, perform simple BFS from each 
unvisited vertex of given graph.

Following is the code when adjacency matrix representation is used for the graph.

C++




// C++ implementation of modified BFS for adjacency matrix
// representation
#include <iostream>
#include <queue>
using namespace std;
void printBFS(int** edges, int V, int start, int* visited);
void BFSHelper(int** edges, int V);
void addEdge(int** edges, int f, int s);
  
void addEdge(int** edges, int f, int s) { edges[f][s] = 1; }
void printBFS(int** edges, int V, int start, int* visited)
{
    if (V == 0)
        return;
    queue<int> BFS;
    BFS.push(start);
    visited[start] = 1;
    while (!BFS.empty()) {
        int data = BFS.front();
        BFS.pop();
        cout << data << " ";
        for (int i = 0; i < V; i++) {
            if (edges[data][i] == 1) {
                if (visited[i] == 0) {
                    BFS.push(i);
                    visited[i] = 1;
                }
            }
        }
    }
}
  
void BFSHelper(int** edges, int V)
{
    if (V == 0)
        return;
    int* visited = new int[V];
    for (int i = 0; i < V; i++) {
        visited[i] = 0;
    }
    for (int i = 0; i < V; i++) {
        if (visited[i] == 0) {
            printBFS(edges, V, i, visited);
        }
    }
}
  
int main()
{
    int V = 5;
    int E = 6;
    if (E == 0) {
        for (int i = 0; i < V; i++) {
            cout << i << " ";
        }
        return 0;
    }
    int** edges = new int*[V];
    for (int i = 0; i < V; i++) {
        edges[i] = new int[V];
        for (int j = 0; j < V; j++) {
            edges[i][j] = 0;
        }
    }
  
    addEdge(edges, 0, 4);
    addEdge(edges, 1, 2);
    addEdge(edges, 1, 3);
    addEdge(edges, 1, 4);
    addEdge(edges, 2, 3);
    addEdge(edges, 3, 4);
  
    BFSHelper(edges, V);
    return 0;
}


Java




// Java implementation of modified BFS for adjacency matrix
// representation
  
import java.io.*;
import java.util.*;
  
class GFG {
  static void addEdge(int[][] edges, int f, int s)
  {
    edges[f][s] = 1;
  }
  
  static void printBFS(int[][] edges, int V, int start,
                       int[] visited)
  {
    if (V == 0)
      return;
    Queue<Integer> BFS = new LinkedList<Integer>();
    BFS.add(start);
    visited[start] = 1;
    while (!BFS.isEmpty()) {
      int data = BFS.poll();
      System.out.print(data + " ");
      for (int i = 0; i < V; i++) {
        if (edges[data][i] == 1) {
          if (visited[i] == 0) {
            BFS.add(i);
            visited[i] = 1;
          }
        }
      }
    }
  }
  
  static void bfsHelper(int[][] edges, int V)
  {
    if (V == 0)
      return;
    int[] visited = new int[V];
    for (int i = 0; i < V; i++) {
      visited[i] = 0;
    }
    for (int i = 0; i < V; i++) {
      if (visited[i] == 0) {
        printBFS(edges, V, i, visited);
      }
    }
    System.out.println();
  }
  
  public static void main(String[] args)
  {
    int V = 5;
    int E = 6;
    if (E == 0) {
      for (int i = 0; i < V; i++) {
        System.out.print(i + " ");
      }
      System.out.println();
      System.exit(0);
    }
    int[][] edges = new int[V][V];
    for (int i = 0; i < V; i++) {
      for (int j = 0; j < V; j++) {
        edges[i][j] = 0;
      }
    }
  
    addEdge(edges, 0, 4);
    addEdge(edges, 1, 2);
    addEdge(edges, 1, 3);
    addEdge(edges, 1, 4);
    addEdge(edges, 2, 3);
    addEdge(edges, 3, 4);
  
    bfsHelper(edges, V);
  }
}
  
// This code is contributed by cavi4762.


Python3




import queue
  
def add_edge(edges, f, s):
    edges[f][s] = 1
  
def print_bfs(edges, V, start, visited):
    if V == 0:
        return
    bfs = queue.Queue()
    bfs.put(start)
    visited[start] = 1
    while not bfs.empty():
        data = bfs.get()
        print(data, end=' ')
        for i in range(V):
            if edges[data][i] == 1:
                if visited[i] == 0:
                    bfs.put(i)
                    visited[i] = 1
  
def bfs_helper(edges, V):
    if V == 0:
        return
    visited = [0] * V
    for i in range(V):
        if visited[i] == 0:
            print_bfs(edges, V, i, visited)
  
if __name__ == "__main__":
    V = 5
    E = 6
    if E == 0:
        for i in range(V):
            print(i, end=' ')
        exit()
  
    edges = [[0 for _ in range(V)] for _ in range(V)]
  
    add_edge(edges, 0, 4)
    add_edge(edges, 1, 2)
    add_edge(edges, 1, 3)
    add_edge(edges, 1, 4)
    add_edge(edges, 2, 3)
    add_edge(edges, 3, 4)
  
    bfs_helper(edges, V)


C#




// C# implementation of modified BFS for adjacency matrix
// representation
  
using System;
using System.Collections.Generic;
  
class Gfg {
  static void AddEdge(int[, ] edges, int f, int s)
  {
    edges[f, s] = 1;
  }
  
  static void PrintBFS(int[, ] edges, int V, int start,
                       int[] visited)
  {
    if (V == 0)
      return;
    Queue<int> BFS = new Queue<int>();
    BFS.Enqueue(start);
    visited[start] = 1;
    while (BFS.Count > 0) {
      int data = BFS.Dequeue();
      Console.Write(data + " ");
      for (int i = 0; i < V; i++) {
        if (edges[data, i] == 1) {
          if (visited[i] == 0) {
            BFS.Enqueue(i);
            visited[i] = 1;
          }
        }
      }
    }
  }
  
  static void BFSHelper(int[, ] edges, int V)
  {
    if (V == 0)
      return;
    int[] visited = new int[V];
    for (int i = 0; i < V; i++) {
      visited[i] = 0;
    }
    for (int i = 0; i < V; i++) {
      if (visited[i] == 0) {
        PrintBFS(edges, V, i, visited);
      }
    }
    Console.WriteLine();
  }
  
  static void Main(string[] args)
  {
    int V = 5;
    int E = 6;
    if (E == 0) {
      for (int i = 0; i < V; i++) {
        Console.Write(i + " ");
      }
      Console.WriteLine();
      Environment.Exit(0);
    }
    int[, ] edges = new int[V, V];
    for (int i = 0; i < V; i++) {
      for (int j = 0; j < V; j++) {
        edges[i, j] = 0;
      }
    }
  
    AddEdge(edges, 0, 4);
    AddEdge(edges, 1, 2);
    AddEdge(edges, 1, 3);
    AddEdge(edges, 1, 4);
    AddEdge(edges, 2, 3);
    AddEdge(edges, 3, 4);
  
    BFSHelper(edges, V);
  }
}
  
// This code is contributed by cavi4762.


Javascript




// Javascript implementation of modified BFS for adjacency matrix representation
 
  class Queue {
    constructor() {
      this.items = [];
    }
 
    // add element to the queue
    push(element) {
      return this.items.push(element);
    }
 
    // remove element from the queue
    pop() {
      if (this.items.length > 0) {
        return this.items.shift();
      }
    }
 
    // view the first element
    front() {
      return this.items[0];
    }
 
    // check if the queue is empty
    empty() {
      return this.items.length == 0;
    }
  }
 
  function addEdge(edges, f, s) {
    edges[f][s] = 1;
  }
  function printBFS(edges, V, start, visited) {
    if (V == 0) return;
    let BFS = new Queue();
    BFS.push(start);
    visited[start] = 1;
    while (!BFS.empty()) {
      data = BFS.front();
      BFS.pop();
      console.log(data);
      for (let i = 0; i < V; i++) {
        if (edges[data][i] == 1) {
          if (visited[i] == 0) {
            BFS.push(i);
            visited[i] = 1;
          }
        }
      }
    }
  }
 
  function BFSHelper(edges, V) {
    if (V == 0) return;
    let visited = new Array(V);
    for (let i = 0; i < V; i++) {
      visited[i] = 0;
    }
    for (let i = 0; i < V; i++) {
      if (visited[i] == 0) {
        printBFS(edges, V, i, visited);
      }
    }
  }
 
  let V = 5;
  let E = 6;
  if (E == 0) {
    for (let i = 0; i < V; i++) {
      console.log(i);
    }
  }
 
  let edges = Array.from(Array(V), () => new Array(V));
  for (let i = 0; i < V; i++) {
    for (let j = 0; j < V; j++) {
      edges[i][j] = 0;
    }
  }
 
  addEdge(edges, 0, 4);
  addEdge(edges, 1, 2);
  addEdge(edges, 1, 3);
  addEdge(edges, 1, 4);
  addEdge(edges, 2, 3);
  addEdge(edges, 3, 4);
 
  BFSHelper(edges, V);


Output

0 4 1 2 3 

The time complexity of this algorithm is O(V + E), where V is the number of vertices and E is the number of edges. This is because we traverse each vertex and each edge once. 

The space complexity is O(V), since we use an array to store the visited vertices.

Following is the code when adjacency list representation is used for the graph.

C++




// C++ implementation of modified BFS
#include<bits/stdc++.h>
using namespace std;
  
// A utility function to add an edge in an
// directed graph.
void addEdge(vector<int> adj[], int u, int v)
{
    adj[u].push_back(v);
}
  
// A utility function to do BFS of graph
// from a given vertex u.
void BFSUtil(int u, vector<int> adj[],
            vector<bool> &visited;)
{
  
    // Create a queue for BFS
    list<int> q;
   
    // Mark the current node as visited and enqueue it
    visited[u] = true;
    q.push_back(u);
   
    // 'i' will be used to get all adjacent vertices 4
    // of a vertex list<int>::iterator i;
   
    while(!q.empty())
    {
        // Dequeue a vertex from queue and print it
        u = q.front();
        cout << u << " ";
        q.pop_front();
   
        // Get all adjacent vertices of the dequeued
        // vertex s. If an adjacent has not been visited, 
        // then mark it visited and enqueue it
        for (int i = 0; i != adj[u].size(); ++i)
        {
            if (!visited[adj[u][i]])
            {
                visited[adj[u][i]] = true;
                q.push_back(adj[u][i]);
            }
        }
    }
}
  
// This function does BFSUtil() for all 
// unvisited vertices.
void BFS(vector<int> adj[], int V)
{
    vector<bool> visited(V, false);
    for (int u=0; u<V; u++)
        if (visited[u] == false)
            BFSUtil(u, adj, visited);
}
  
// Driver code
int main()
{
    int V = 5;
    vector<int> adj[V];
  
    addEdge(adj, 0, 4);
    addEdge(adj, 1, 2);
    addEdge(adj, 1, 3);
    addEdge(adj, 1, 4);
    addEdge(adj, 2, 3);
    addEdge(adj, 3, 4);
    BFS(adj, V);
    return 0;
}


Java




// Java implementation of modified BFS 
import java.util.*;
public class graph 
{
    //Implementing graph using HashMap
    static HashMap<Integer,LinkedList<Integer>> graph=new HashMap<>();
  
    //utility function to add edge in an undirected graph
public static void addEdge(int a,int b)
{
    if(graph.containsKey(a))
    {
        LinkedList<Integer> l=graph.get(a);
        l.add(b);
        graph.put(a,l);
    }
    else
    {
        LinkedList<Integer> l=new LinkedList<>();
        l.add(b);
        graph.put(a,l);
    }
}
  
//Helper function for BFS 
public static void bfshelp(int s,ArrayList<Boolean> visited)
{
    // Create a queue for BFS 
    LinkedList<Integer> q=new LinkedList<>();
      
    // Mark the current node as visited and enqueue it 
    q.add(s);
    visited.set(s,true);
      
    while(!q.isEmpty())
    {
        // Dequeue a vertex from queue and print it 
        int f=q.poll();
        System.out.print(f+" ");
          
        //Check whether the current node is 
                //connected to any other node or not
        if(graph.containsKey(f))
        {
        Iterator<Integer> i=graph.get(f).listIterator();
          
        // Get all adjacent vertices of the dequeued 
        // vertex f. If an adjacent has not been visited,  
        // then mark it visited and enqueue it 
          
            while(i.hasNext())
            {
                int n=i.next();
                if(!visited.get(n))
                {
                visited.set(n,true);
                q.add(n);
                }
            }
        }
    }
      
}
  
//BFS function to check each node
public static void bfs(int vertex)
{
    ArrayList<Boolean> visited=new ArrayList<Boolean>();
    //Marking each node as unvisited
    for(int i=0;i<vertex;i++)
    {
        visited.add(i,false);
    }
    for(int i=0;i<vertex;i++)
    {
        //Checking whether the node is visited or not
        if(!visited.get(i))
        {
            bfshelp(i,visited);
        }
    }
}
  
//Driver Code-The main function
    public static void main(String[] args) 
    {
        int v=5;
        addEdge(0, 4); 
        addEdge(1, 2); 
        addEdge(1, 3); 
        addEdge(1, 4); 
        addEdge(2, 3); 
        addEdge(3, 4); 
        bfs(v);
    }
  
}


Python3




# Python3 implementation of modified BFS 
import queue
  
# A utility function to add an edge 
# in an undirected graph. 
def addEdge(adj, u, v):
    adj[u].append(v)
  
# A utility function to do BFS of 
# graph from a given vertex u. 
def BFSUtil(u, adj, visited):
  
    # Create a queue for BFS 
    q = queue.Queue()
      
    # Mark the current node as visited
    # and enqueue it 
    visited[u] = True
    q.put(u) 
      
    # 'i' will be used to get all adjacent 
    # vertices 4 of a vertex list<int>::iterator i 
      
    while(not q.empty()):
          
        # Dequeue a vertex from queue 
        # and print it 
        u = q.queue[0] 
        print(u, end = " ") 
        q.get() 
      
        # Get all adjacent vertices of the 
        # dequeued vertex s. If an adjacent 
        # has not been visited, then mark 
        # it visited and enqueue it 
        i = 0
        while i != len(adj[u]):
            if (not visited[adj[u][i]]):
                    visited[adj[u][i]] = True
                    q.put(adj[u][i])
            i += 1
  
# This function does BFSUtil() for all 
# unvisited vertices. 
def BFS(adj, V):
    visited = [False] * V 
    for u in range(V):
        if (visited[u] == False): 
            BFSUtil(u, adj, visited)
  
# Driver code 
if __name__ == '__main__':
  
    V = 5
    adj = [[] for i in range(V)] 
  
    addEdge(adj, 0, 4) 
    addEdge(adj, 1, 2) 
    addEdge(adj, 1, 3) 
    addEdge(adj, 1, 4) 
    addEdge(adj, 2, 3) 
    addEdge(adj, 3, 4) 
    BFS(adj, V)
  
# This code is contributed by PranchalK


C#




// C# implementation of modified BFS 
using System;
using System.Collections.Generic;
  
class Graph 
{ 
    //Implementing graph using Dictionary 
    static Dictionary<int,List<int>> graph = 
            new Dictionary<int,List<int>>(); 
  
//utility function to add edge in an undirected graph 
public static void addEdge(int a, int b) 
{ 
    if(graph.ContainsKey(a)) 
    { 
        List<int> l = graph[a]; 
        l.Add(b); 
        if(graph.ContainsKey(a))
            graph[a] = l;
        else
            graph.Add(a,l); 
    } 
    else
    { 
        List<int> l = new List<int>(); 
        l.Add(b); 
        graph.Add(a, l); 
    } 
} 
  
// Helper function for BFS 
public static void bfshelp(int s, List<Boolean> visited) 
{ 
    // Create a queue for BFS 
    List<int> q = new List<int>(); 
      
    // Mark the current node as visited and enqueue it 
    q.Add(s); 
    visited.RemoveAt(s);
    visited.Insert(s,true); 
      
    while(q.Count != 0) 
    { 
        // Dequeue a vertex from queue and print it 
        int f = q[0]; 
        q.RemoveAt(0);
        Console.Write(f + " "); 
          
        //Check whether the current node is 
        //connected to any other node or not 
        if(graph.ContainsKey(f)) 
        { 
          
        // Get all adjacent vertices of the dequeued 
        // vertex f. If an adjacent has not been visited, 
        // then mark it visited and enqueue it 
          
            foreach(int iN in graph[f]) 
            { 
                int n = iN; 
                if(!visited[n]) 
                { 
                    visited.RemoveAt(n);
                    visited.Insert(n, true); 
                    q.Add(n); 
                } 
            } 
        } 
    } 
      
} 
  
// BFS function to check each node 
public static void bfs(int vertex) 
{ 
    List<Boolean> visited = new List<Boolean>(); 
      
    // Marking each node as unvisited 
    for(int i = 0; i < vertex; i++) 
    { 
        visited.Insert(i, false); 
    } 
    for(int i = 0; i < vertex; i++) 
    { 
        // Checking whether the node is visited or not 
        if(!visited[i]) 
        { 
            bfshelp(i, visited); 
        } 
    } 
} 
  
// Driver Code 
public static void Main(String[] args) 
{ 
    int v = 5; 
    addEdge(0, 4); 
    addEdge(1, 2); 
    addEdge(1, 3); 
    addEdge(1, 4); 
    addEdge(2, 3); 
    addEdge(3, 4); 
    bfs(v); 
} 
} 
  
// This code is contributed by Rajput-Ji


Javascript




// JavaScript implementation of modified BFS 
class Graph {
  constructor() {
    this.graph = new Map(); // Implementing graph using Map
  }
  
  // utility function to add edge in an undirected graph
  addEdge(a, b) {
    if (this.graph.has(a)) {
      let l = this.graph.get(a);
      l.push(b);
      this.graph.set(a, l);
    } else {
      this.graph.set(a, [b]);
    }
  }
  
  // Helper function for BFS 
  bfshelp(s, visited) {
    // Create a queue for BFS 
    let q = [];
    // Mark the current node as visited and enqueue it 
    q.push(s);
    visited[s] = true;
  
    while (q.length > 0) {
      // Dequeue a vertex from queue and print it 
      let f = q.shift();
      console.log(f + " ");
  
      // Check whether the current node is connected to any other node or not
      if (this.graph.has(f)) {
        let l = this.graph.get(f);
        for (let n of l) {
          // Get all adjacent vertices of the dequeued vertex f. 
          // If an adjacent has not been visited, then mark it visited and enqueue it 
          if (!visited[n]) {
            visited[n] = true;
            q.push(n);
          }
        }
      }
    }
  }
  
  // BFS function to check each node
  bfs(vertex) {
    let visited = Array(vertex).fill(false);
    // Marking each node as unvisited
    for (let i = 0; i < vertex; i++) {
      // Checking whether the node is visited or not
      if (!visited[i]) {
        this.bfshelp(i, visited);
      }
    }
  }
}
  
// Driver Code-The main function
let g = new Graph();
let v = 5;
g.addEdge(0, 4); 
g.addEdge(1, 2); 
g.addEdge(1, 3); 
g.addEdge(1, 4); 
g.addEdge(2, 3); 
g.addEdge(3, 4); 
g.bfs(v);
  
  
//This code is contributed by shivamsharma215


Output

0 4 1 2 3 

The time complexity of the given BFS algorithm is O(V + E), where V is the number of vertices and E is the number of edges in the graph. 

The space complexity is also O(V + E) since we need to store the adjacency list and the visited array.

 



Previous Article
Next Article

Similar Reads

Maximize count of nodes disconnected from all other nodes in a Graph
Given two integers N and E which denotes the number of nodes and the number of edges of an undirected graph, the task is to maximize the number of nodes which is not connected to any other node in the graph, without using any self-loops. Examples: Input: N = 5, E = 1 Output: 3 Explanation: Since there is only 1 edge in the graph which can be used t
4 min read
Depth First Search or DFS for disconnected Graph
Given a Disconnected Graph, the task is to implement DFS or Depth First Search Algorithm for this Disconnected Graph. Example: Input: Output: 0 1 2 3 Algorithm for DFS on Disconnected Graph:In the post for Depth First Search for Graph, only the vertices reachable from a given source vertex can be visited. All the vertices may not be reachable from
7 min read
Count single node isolated sub-graphs in a disconnected graph
A disconnected Graph with N vertices and K edges is given. The task is to find the count of singleton sub-graphs. A singleton graph is one with only single vertex. Examples: Input : Vertices : 6 Edges : 1 2 1 3 5 6 Output : 1 Explanation : The Graph has 3 components : {1-2-3}, {5-6}, {4} Out of these, the only component forming singleton graph is {
4 min read
Diameters for each node of Tree after connecting it with given disconnected component
Given a Tree having N nodes connected by N ? 1 edge and a single disconnected node, the task is to find the diameters for each node of the given Tree after connecting it with the given disconnected component. Example: Input: Output: 3 3 4 4 4 4 Explanation: Initially diameter of tree = 3. If an edge is added between node 1 and node 7, then the diam
11 min read
Print the lexicographically smallest BFS of the graph starting from 1
Given a connected graph with N vertices and M edges. The task is to print the lexicographically smallest BFS traversal of the graph starting from 1. Note: The vertices are numbered from 1 to N.Examples: Input: N = 5, M = 5 Edges: 1 4 3 4 5 4 3 2 1 5 Output: 1 4 3 2 5 Start from 1, go to 4, then to 3 and then to 2 and to 5. Input: N = 3, M = 2 Edges
7 min read
When to use DFS or BFS to solve a Graph problem?
Generally, when we come across a graph problem, we might need to traverse the structure of the given graph or tree to find our solution to the problem. Our problem might be : To search for a particular node in the graph.To find the shortest distance from a node to any other node or to every other node.To count all the nodes.Or there can be more com
7 min read
Traversal of a Graph in lexicographical order using BFS
C/C++ Code // C++ program to implement // the above approach #include &lt;bits/stdc++.h&gt; using namespace std; // Function to traverse the graph in // lexicographical order using BFS void LexiBFS(map&lt;char, set&lt;char&gt; &gt;&amp; G, char S, map&lt;char, bool&gt;&amp; vis) { // Stores nodes of the graph // at each level queue&lt;char&gt; q; /
9 min read
Detect Cycle in a Directed Graph using BFS
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains two cycles 0-&gt;1-&gt;2-&gt;3-&gt;0 and 2-&gt;4-&gt;2, so your function must return true. Recommended: Please solve it on "PRACTICE" f
11 min read
Check if a given directed graph is strongly connected | Set 2 (Kosaraju using BFS)
Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pairs of vertices. There are different methods to check the connectivity of directed graph but one of the optimized method is Kosaraju’s DFS based simple algorithm. Kosaraju’s BFS based simple al
14 min read
0-1 BFS (Shortest Path in a Binary Weight Graph)
Given a graph where every edge has weight as either 0 or 1. A source vertex is also given in the graph. Find the shortest path from the source vertex to every other vertex.  For Example:  Input : Source Vertex = 0 and below graph Having vertices like(u,v,w): Edges: [[0,1,0], [0, 7, 1], [1,2,1], [1, 7, 1], [2, 3, 0], [2, 5, 0], [2, 8, 1], [3, 4, 1],
9 min read
Detect cycle in an undirected graph using BFS
Given an undirected graph, how to check if there is a cycle in the graph? For example, the following graph has a cycle of 1-0-2-1.  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.We have discussed cycle detection for the directed graph. We have also discussed a union-find algorithm for cycle detection in undirect
5 min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
Islands in a graph using BFS
Given a binary 2D matrix, find the number of islands. A group of connected 1s forms an island. For example, the below matrix contains 4 islands. Example:  Input: mat[][] = {{1, 1, 0, 0, 0},                           {0, 1, 0, 0, 1},                           {1, 0, 0, 1, 1},                          {0, 0, 0, 0, 0},                         {1, 0, 1
14 min read
Water Jug problem using BFS
You are given an m liter jug and a n liter jug. Both the jugs are initially empty. The jugs don’t have markings to allow measuring smaller quantities. You have to use the jugs to measure d liters of water where d is less than n. (X, Y) corresponds to a state where X refers to the amount of water in Jug1 and Y refers to the amount of water in Jug2 D
15+ min read
Diameter of n-ary tree using BFS
N-ary tree refers to the rooted tree in which each node having atmost k child nodes. The diameter of n-ary tree is the longest path between two leaf nodes. Various approaches have already been discussed to compute diameter of tree. Diameter of an N-ary tree Diameter of a Binary Tree in O(n) Diameter of a Binary Tree Diameter of a tree using DFS Thi
7 min read
Count the number of nodes at given level in a tree using BFS.
Given a tree represented as an undirected graph. Count the number of nodes at a given level l. It may be assumed that vertex 0 is the root of the tree. Examples: Input : 7 0 1 0 2 1 3 1 4 1 5 2 6 2 Output : 4 Input : 6 0 1 0 2 1 3 2 4 2 5 2 Output : 3 BFS is a traversing algorithm that starts traversing from a selected node (source or starting node
9 min read
BFS using vectors &amp; queue as per the algorithm of CLRS
Breadth-first search traversal of a graph using the algorithm given in CLRS book. BFS is one of the ways to traverse a graph. It is named so because it expands the frontier between discovered and undiscovered vertices uniformly across the breadth of the frontier. What it means is that the algorithm first discovers all the vertices connected to "u"
11 min read
Coin Change | BFS Approach
Given an integer X and an array arr[] of length N consisting of positive integers, the task is to pick minimum number of integers from the array such that they sum up to N. Any number can be chosen infinite number of times. If no answer exists then print -1.Examples: Input: X = 7, arr[] = {3, 5, 4} Output: 2 The minimum number elements will be 2 as
6 min read
Illustrate the difference in peak memory consumption between DFS and BFS
To understand this let's take a binary tree If we conduct BFS in this tree: In level 0 there is one node in the memory In level 1 there are two nodes in the memory In level 2 there are four nodes in the memory In level 3 there are eight nodes in the memory But in the case of DFS in this tree, you'll never have more than 4 nodes in memory The differ
1 min read
Implementation of BFS using adjacency matrix
Breadth First Search (BFS) has been discussed in this article which uses adjacency list for the graph representation. In this article, adjacency matrix will be used to represent the graph. Adjacency matrix representation: In adjacency matrix representation of a graph, the matrix mat[][] of size n*n (where n is the number of vertices) will represent
7 min read
Word Ladder - Set 2 ( Bi-directional BFS )
Given a dictionary, and two words start and target (both of the same length). Find length of the smallest chain from start to target if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the target word exists in the dicti
15+ min read
Find integral points with minimum distance from given set of integers using BFS
Given an integer array A[] of length N and an integer K. The task is to find K distinct integral points that are not present in the given array such that the sum of their distances from the nearest point in A[] is minimized. An integral point is defined as the point with both the coordinates as integers. Also, in the x-axis, we don't need to consid
9 min read
Check if the given permutation is a valid BFS of a given Tree
Given a tree with N nodes numbered from 1 to N and a permutation array of numbers from 1 to N. Check if it is possible to obtain the given permutation array by applying BFS (Breadth First Traversal) on the given tree.Note: Traversal will always start from 1.Example: Input: arr[] = { 1 5 2 3 4 6 } Edges of the given tree: 1 - 2 1 - 5 2 - 3 2 - 4 5 -
10 min read
Distance of each node of a Binary Tree from the root node using BFS
Given a Binary tree consisting of N nodes with values in the range [1, N], the task is to find the distance from the root node to every node of the tree. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 Output: 0 1 1 2 2 2 Explanation: The distance from the root to node 1 is 0. The distance from the root to node 2 is 1. The distance from the root to node 3 i
9 min read
Breadth First Traversal ( BFS ) on a 2D array
Given a matrix of size M x N consisting of integers, the task is to print the matrix elements using Breadth-First Search traversal. Examples: Input: grid[][] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}, {13, 14, 15, 16}}Output: 1 2 5 3 6 9 4 7 10 13 8 11 14 12 15 16 Input: grid[][] = {{-1, 0, 0, 1}, {-1, -1, -2, -1}, {-1, -1, -1, -1}, {0, 0, 0,
9 min read
Find count of pair of nodes at even distance | Set 2 (Using BFS)
Given a connected acyclic graph with N nodes numbered from 1 to N and N-1 edges, find out the pair of nodes that are at even distance from each other. Note: The graph is represented in the form of an adjacency list. Examples: Input: N = 3, graph = {{}, {2}, {1, 3}, {2}}Output:1Explanation: Here there are three pairs {1, 2}, {1, 3}and {2, 3} and onl
8 min read
Difference between BFS and Dijkstra's algorithms when looking for shortest path?
What is Dijkstra's Algorithm? Dijkstra's Algorithm is used for finding the shortest path between any two vertices of a graph. It uses a priority queue for finding the shortest path. For more detail about Dijkstra's Algorithm, you can refer to this article. What is BFS Algorithm? Breadth First Search (BFS) algorithm traverses a graph in a bread towa
2 min read
Level of Each node in a Tree from source node (using BFS)
Given a tree with v vertices, find the level of each node in a tree from the source node. Examples: Input : Output : Node Level 0 0 1 1 2 1 3 2 4 2 5 2 6 2 7 3 Explanation : Input: Output : Node Level 0 0 1 1 2 1 3 2 4 2 Explanation: Approach: BFS(Breadth-First Search) is a graph traversal technique where a node and its neighbours are visited first
8 min read
Applications, Advantages and Disadvantages of Breadth First Search (BFS)
We have earlier discussed Breadth First Traversal Algorithm for Graphs. Here in this article, we will see the applications, advantages, and disadvantages of the Breadth First Search. Applications of Breadth First Search: 1. Shortest Path and Minimum Spanning Tree for unweighted graph: In an unweighted graph, the shortest path is the path with the l
4 min read
Traversing directory in Java using BFS
Given a directory, print all files and folders present in directory tree rooted with given directory. We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from queue. If the popped item is a directory, get list o
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg