You are on page 1of 2

21BCM027 PRACTICAL 10 KAVISH SHAH

PROGRAMMING WITH DATA STRUCTURES


Q - Write a program to obtain a spanning tree of a connected
undirected graph using appropriate data structure.

CODE:
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
int main(){
int v;
printf("\nEnter number of vertices in the graph : ");
scanf("%d",&v);
int G[v][v];
for (int i=0; i<v; i++){
for (int j = 0; j < v; j++){
printf("\nEnter weight of the edge between vertex %d and vertex %d (0
if no edge): ",i,j);
scanf("%d",&G[i][j]);
}
}
int edges=0;
int selected[v];
for (int i = 0; i < v; i++){
selected[i] = false;
}
selected[0] = true;

int x;
int y;
printf("Edge : Weight\n");
while (edges < v - 1){
int min = __INT_MAX__;
x = 0;
y = 0;
for (int i = 0; i < v; i++){
if (selected[i]){
for (int j = 0; j < v; j++){
if (!selected[j] && G[i][j]){
if (min > G[i][j]){
min = G[i][j];
x = i;
y = j;
}
}
}
}
}
printf("%d - %d : %d\n", x, y, G[x][y]);
21BCM027 PRACTICAL 10 KAVISH SHAH

selected[y] = true;
edges++;
}
return 0;
}

OUTPUT SNIPPET:

You might also like