Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<stdio.h>
- int V, count = 0;
- int queue[50], qpos = -1, qlen = -1;
- //Function declarations
- void Init_Mat(int mat[50][50], int visit[50]);
- void Addedge(int mat[50][50], int source, int dest);
- void DisplayAdjMat(int mat[50][50]);
- void BFS(int node, int visit[50], int mat[50][50]);
- int main()
- {
- int i, j, AdjMat[50][50];
- int edge_add_choice = 1;
- int visited[50];
- int Edge_A, Edge_B;
- //Taking input for the number of nodes in the graph
- printf("Enter the amount of nodes : ");
- scanf("%d", &V);
- //Initializing the Adjacency Matrix
- Init_Mat(AdjMat, visited);
- //Do-While loop to take inputs for the graph
- do
- {
- printf("\nEnter the Vertice 1 of the Edge : ");
- scanf("%d", &Edge_A);
- printf("Enter the Vertice 2 of the Edge : ");
- scanf("%d", &Edge_B);
- Addedge(AdjMat, Edge_A, Edge_B);
- printf("\nWhat do you want to do now ?\n1. Add another Edge\n2. Stop adding edges\n");
- scanf("%d", &edge_add_choice);
- } while (edge_add_choice == 1);
- DisplayAdjMat(AdjMat);
- printf("\nThe required BFS for the graph will be : \n");
- BFS(0, visited, AdjMat);
- return 0;
- }
- //Initialize the adjacency matrix and visited array with 0 in all elements
- void Init_Mat(int mat[50][50], int visit[50])
- {
- for(int i = 0; i < V; i++)
- {
- visit[i] = 0;
- for(int j = 0; j < V; j++)
- {
- mat[i][j] = 0;
- }
- }
- }
- //Add adjacency values to the matrix by using the edges of the graph
- void Addedge(int mat[50][50], int source, int dest)
- {
- mat[source][dest] = 1;
- mat[dest][source] = 1;
- }
- //Display the Adjacency Matrix
- void DisplayAdjMat(int mat[50][50])
- {
- printf("\nDisplaying the Adjacency Matrix : \n");
- for(int i = 0; i < V; i++)
- {
- for(int j = 0; j < V; j++)
- {
- printf("%d ", mat[i][j]);
- }
- printf("\n");
- }
- }
- //Depth First Search
- void BFS(int node, int visit[50], int mat[50][50])
- {
- int j;
- printf("%d", node);
- count++;
- if(count != V)
- {
- printf("->");
- }
- visit[node] = 1;
- for(j=0; j<V; j++)
- {
- if(mat[node][j] && !visit[j])
- {
- qlen++;
- queue[qlen] = j;
- visit[j] = 1;
- }
- }
- if(count != V)
- {
- BFS(queue[++qpos], visit, mat);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment