Patel Princy Chiragbhai
Branch – Cyber Security
Sem – 3
Batch – CSE35
Enrollment No. - 22162171020
Institute of Computer Technology
B. Tech Computer Science and Engineering
Subject: Data Structures
Practical 20
Imagine you have a map of interconnected cities, and you want to find a
path from one city to another. You decide to use Depth-First Search
(DFS) to explore the connections between cities. This C program
models the cities as vertices in a graph and the roads as edges,
allowing you to perform a DFS traversal to find a path between two
cities.
Code :-
#include <stdio.h>
#include <stdbool.h>
#define MAX_CITIES 100
int graph[MAX_CITIES][MAX_CITIES];
int numCities;
bool visited[MAX_CITIES];
void initializeGraph(int num)
{
numCities = num;
int i, j;
for (i = 0; i < numCities; i++)
{
visited[i] = false;
for (j = 0; j < numCities; j++)
{
graph[i][j] = 0;
}
}
}
void addEdge(int from, int to)
{
graph[from][to] = 1;
graph[to][from] = 1;
}
bool DFS(int start, int end)
{
if (start == end)
{
printf("%d ", start);
return true;
}
visited[start] = true;
int city;
for (city = 0; city < numCities; city++)
{
if (graph[start][city] && !visited[city])
{
if (DFS(city, end))
{
printf("%d ", start);
return true;
}
}
}
return false;
}
int main()
{
initializeGraph(5);
addEdge(0, 1);
addEdge(1, 2);
addEdge(2, 3);
addEdge(3, 4);
addEdge(0, 4);
int startCity = 0;
int endCity = 3;
printf("Path from City %d to City %d: ", startCity, endCity);
if (DFS(startCity, endCity))
{
printf("%d\n", endCity);
}
else
{
printf("No path found.\n");
}
return 0;
}
Output:-