Design, Develop and implement a program in C for the following operations on 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 DFS/BFS method.
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
#define bool int
#define true 1
#define false 0
int n; // number of cities
int adj[MAX][MAX]; // adjacency matrix
bool visited[MAX]; // to keep track of visited nodes
void createGraph() {
int i, j, x;
printf("Enter the number of cities: ");
scanf("%d", &n);
printf("Enter the adjacency matrix:\n");
for (i = 0; i< n; i++) {
for (j = 0; j< n; j++) {
scanf("%d", &adj[i][j]);
}
}
}
void DFS(int start) {
int i;
printf("%d ", start);
visited[start] = true;
for (i = 0; i < n; i++) {
if (adj[start][i] == 1 && !visited[i]) {
DFS(i);
}
}
}
void BFS(int start) {
int i, queue[MAX], front = 0, rear = 0;
printf("%d ", start);
visited[start] = true;
queue[rear++] = start;
while (front != rear) {
int curr = queue[front++];
for (i = 0; i < n; i++) {
if (adj[curr][i] == 1 && !visited[i]) {
printf("%d ", i);
visited[i] = true;
queue[rear++] = i;
}
}
}
}
int main() {
int start;
createGraph();
printf("Enter the starting node: ");
scanf("%d", &start);
printf("DFS: ");
DFS(start);
printf("\n");
// reset visited array
for (int i = 0; i < n; i++) {
visited[i] = false;
}
printf("BFS: ");
BFS(start);
return 0;
}