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 the edges of the graph where mat[i][j] = 1 represents that there is an edge between the vertices i and j while mat[i][j] = 0 represents that there is no edge between the vertices i and j.
Below is the adjacency matrix representation of the graph shown in the above image:
0 1 2 3 0 0 1 1 0 1 1 0 0 1 2 1 0 0 0 3 0 1 0 0
Examples:
Input: source = 0
Output: 0 1 2 3
Input: source = 1
Output:1 0 2 3 4
Approach:
Create a matrix of size n*n where every element is 0 representing there is no edge in the graph.
Now, for every edge of the graph between the vertices i and j set mat[i][j] = 1.
After the adjacency matrix has been created and filled, find the BFS traversal of the graph as described in this post.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach#include<bits/stdc++.h>usingnamespacestd;vector<vector<int>>adj;// function to add edge to the graphvoidaddEdge(intx,inty){adj[x][y]=1;adj[y][x]=1;}// Function to perform BFS on the graphvoidbfs(intstart){// Visited vector to so that// a vertex is not visited more than once// Initializing the vector to false as no// vertex is visited at the beginningvector<bool>visited(adj.size(),false);vector<int>q;q.push_back(start);// Set source as visitedvisited[start]=true;intvis;while(!q.empty()){vis=q[0];// Print the current nodecout<<vis<<" ";q.erase(q.begin());// For every adjacent vertex to the current vertexfor(inti=0;i<adj[vis].size();i++){if(adj[vis][i]==1&&(!visited[i])){// Push the adjacent node to the queueq.push_back(i);// Setvisited[i]=true;}}}}// Driver codeintmain(){// number of verticesintv=5;// adjacency matrixadj=vector<vector<int>>(v,vector<int>(v,0));addEdge(0,1);addEdge(0,2);addEdge(1,3);// perform bfs on the graphbfs(0);}
Java
// Java implementation of the approachimportjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;classGFG{staticclassGraph{// Number of vertexintv;// Number of edgesinte;// Adjacency matrixint[][]adj;// Function to fill the empty// adjacency matrixGraph(intv,inte){this.v=v;this.e=e;adj=newint[v][v];for(introw=0;row<v;row++)Arrays.fill(adj[row],0);}// Function to add an edge to the graphvoidaddEdge(intstart,inte){// Considering a bidirectional edgeadj[start][e]=1;adj[e][start]=1;}// Function to perform BFS on the graphvoidBFS(intstart){// Visited vector to so that// a vertex is not visited more than once// Initializing the vector to false as no// vertex is visited at the beginningboolean[]visited=newboolean[v];Arrays.fill(visited,false);List<Integer>q=newArrayList<>();q.add(start);// Set source as visitedvisited[start]=true;intvis;while(!q.isEmpty()){vis=q.get(0);// Print the current nodeSystem.out.print(vis+" ");q.remove(q.get(0));// For every adjacent vertex to// the current vertexfor(inti=0;i<v;i++){if(adj[vis][i]==1&&(!visited[i])){// Push the adjacent node to// the queueq.add(i);// Setvisited[i]=true;}}}}}// Driver codepublicstaticvoidmain(String[]args){intv=5,e=4;// Create the graphGraphG=newGraph(v,e);G.addEdge(0,1);G.addEdge(0,2);G.addEdge(1,3);G.BFS(0);}}// This code is contributed by sanjeev2552
Python3
# Python3 implementation of the approach classGraph:adj=[]# Function to fill empty adjacency matrixdef__init__(self,v,e):self.v=vself.e=eGraph.adj=[[0foriinrange(v)]forjinrange(v)]# Function to add an edge to the graphdefaddEdge(self,start,e):# Considering a bidirectional edgeGraph.adj[start][e]=1Graph.adj[e][start]=1# Function to perform DFS on the graphdefBFS(self,start):# Visited vector to so that a# vertex is not visited more than # once Initializing the vector to # false as no vertex is visited at# the beginning visited=[False]*self.vq=[start]# Set source as visitedvisited[start]=Truewhileq:vis=q[0]# Print current nodeprint(vis,end=' ')q.pop(0)# For every adjacent vertex to # the current vertexforiinrange(self.v):if(Graph.adj[vis][i]==1and(notvisited[i])):# Push the adjacent node # in the queueq.append(i)# setvisited[i]=True# Driver codev,e=5,4# Create the graphG=Graph(v,e)G.addEdge(0,1)G.addEdge(0,2)G.addEdge(1,3)# Perform BFSG.BFS(0)# This code is contributed by ng24_7
C#
// C# implementation of the approachusingSystem;usingSystem.Collections.Generic;publicclassGFG{classGraph{// Number of vertexpublicintv;// Number of edgespublicinte;// Adjacency matrixpublicint[,]adj;// Function to fill the empty// adjacency matrixpublicGraph(intv,inte){this.v=v;this.e=e;adj=newint[v,v];for(introw=0;row<v;row++)for(intcol=0;col<v;col++)adj[row,col]=0;}// Function to add an edge to the graphpublicvoidaddEdge(intstart,inte){// Considering a bidirectional edgeadj[start,e]=1;adj[e,start]=1;}// Function to perform BFS on the graphpublicvoidBFS(intstart){// Visited vector to so that// a vertex is not visited more than once// Initializing the vector to false as no// vertex is visited at the beginningbool[]visited=newbool[v];List<int>q=newList<int>();q.Add(start);// Set source as visitedvisited[start]=true;intvis;while(q.Count!=0){vis=q[0];// Print the current nodeConsole.Write(vis+" ");q.Remove(q[0]);// For every adjacent vertex to// the current vertexfor(inti=0;i<v;i++){if(adj[vis,i]==1&&(!visited[i])){// Push the adjacent node to// the queueq.Add(i);// Setvisited[i]=true;}}}}}// Driver codepublicstaticvoidMain(String[]args){intv=5,e=4;// Create the graphGraphG=newGraph(v,e);G.addEdge(0,1);G.addEdge(0,2);G.addEdge(1,3);G.BFS(0);}}// This code is contributed by shikhasingrajput
JavaScript
// JavaScript implementation of the approachconstadj=[];// function to add edge to the graphfunctionaddEdge(x,y){adj[x][y]=1;adj[y][x]=1;}// Function to perform BFS on the graphfunctionbfs(start){// Visited array to keep track of visited nodes// Initializing the array with all false values as no vertex // is visited at the beginningconstvisited=Array(adj.length).fill(false);constq=[];q.push(start);// Set source as visitedvisited[start]=true;letvis;while(q.length>0){vis=q.shift();// Print the current nodeconsole.log(vis+" ");// For every adjacent vertex to the current vertexfor(leti=0;i<adj[vis].length;i++){if(adj[vis][i]===1&&!visited[i]){// Push the adjacent node to the queueq.push(i);// Set the adjacent node as visitedvisited[i]=true;}}}}// Driver code// number of verticesconstv=5;// adjacency matrixfor(leti=0;i<v;i++){adj[i]=Array(v).fill(0);}addEdge(0,1);addEdge(0,2);addEdge(1,3);// perform bfs on the graphbfs(0);
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.