# Implementation of BFS using adjacency matrix

• Difficulty Level : Easy
• Last Updated : 03 Feb, 2022

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#

Output:

0 1 2 3

Time Complexity: O(N*N)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up