0% found this document useful (0 votes)
28 views

BFS

The document contains a C program that creates a graph of N cities using an adjacency matrix and implements a Breadth-First Search (BFS) algorithm to print all nodes reachable from a given starting node in a directed graph. It includes functions to initialize the graph, perform BFS, and handle user input for the adjacency matrix and starting vertex. The program is designed to display reachable nodes in a user-friendly format.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

BFS

The document contains a C program that creates a graph of N cities using an adjacency matrix and implements a Breadth-First Search (BFS) algorithm to print all nodes reachable from a given starting node in a directed graph. It includes functions to initialize the graph, perform BFS, and handle user input for the adjacency matrix and starting vertex. The program is designed to display reachable nodes in a user-friendly format.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

[PART B 8TH QUESTION]

Program for the following operation on the graph (G) of cities

(a)Create a graph of N cities using Adjacency Matrix

(b)Print all the nodes reachable from a given starting node in a diagraph using BFS method

#include <stdio.h>

int a[50][50], n, v[50];

int q[50], front = 0, rear = -1;

void bfs(int start)

int i;

printf("%d ", start + 1); // display as 1-based

v[start] = 1;

q[++rear] = start;

while (front <= rear)

int cur = q[front++];

for (i = 0; i < n; i++)

if (a[cur][i] == 1 && v[i] == 0)

printf("%d ", i + 1);

v[i] = 1;

q[++rear] = i;

void main()
{

int i, j, start;

clrscr();

printf("Enter number of vertices: ");

scanf("%d", &n);

printf("Enter adjacency matrix (0 or 1):\n");

for (i = 0; i < n; i++)

for (j = 0; j < n; j++)

scanf("%d", &a[i][j]);

printf("Enter starting vertex (1 to %d): ", n);

scanf("%d", &start);

start--; // adjust for 0-based indexing

for (i = 0; i < n; i++)

v[i] = 0;

printf("Nodes reachable from vertex %d: ", start + 1);

bfs(start);

getch();

You might also like