Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
24 views3 pages

DFS Pathfinding C Program

This JSON summarizes a C program that models cities as vertices in a graph and roads as edges, allowing depth-first search traversal to find a path between two cities. The program initializes a graph, adds edges between cities, and performs DFS to print a path between a start and end city if one exists.
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)
24 views3 pages

DFS Pathfinding C Program

This JSON summarizes a C program that models cities as vertices in a graph and roads as edges, allowing depth-first search traversal to find a path between two cities. The program initializes a graph, adds edges between cities, and performs DFS to print a path between a start and end city if one exists.
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/ 3

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:-

You might also like