Exp 10 Harmeet
Exp 10 Harmeet
Aim: From a given starting node in a digraph, print all the nodes reachable by using BFS/DFS
method.
Theory:
Graph Traversal is a technique used to systematically visit all the nodes in a graph. Two widely
used algorithms for this are Breadth-First Search (BFS) and Depth-First Search (DFS).
Although both aim to explore nodes and edges, they follow different approaches:
• Breadth-First Search (BFS): BFS explores the graph level by level, visiting all
neighboring nodes at the current depth before moving on to the next level. It typically
employs a queue to track the next node to visit.
• Depth-First Search (DFS): DFS explores the graph by going as deep as possible along
each path before backtracking. It continues down a branch until it finds a node with no
unvisited neighbors. DFS can be implemented recursively (using the call stack) or with
an explicit stack.
Pseudo Code:
BFS
FUNCTION BFS(graph, start):
INITIALIZE an empty queue
INITIALIZE a set for visited nodes
ENQUEUE start node into the queue
MARK start node as visited
DFS
FUNCTION DFS(graph, node, visited):
IF node is not in visited THEN:
PRINT node
MARK node as visited
Code:
#include <iostream>
#include <queue>
using namespace std;
q.push(start);
visited[start] = true;
cout << "BFS from node " << start << ": ";
while (!q.empty()) {
int node = q.front();
q.pop();
cout << node << " ";
int main() {
int graph[MAX_NODES][MAX_NODES] = {
{0, 1, 1, 0, 0, 0},
{0, 0, 1, 1, 0, 0},
{0, 0, 0, 0, 1, 0},
{0, 0, 0, 0, 0, 1},
{0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0}
};
int startNode = 0;
return 0;
}
Output
Aim: Implement Traveling Salesman problem based on Branch and Bound technique.
Theory:
The Traveling Salesman Problem (TSP) is a well-known optimization challenge where a
salesman must visit a collection of cities exactly once and return to the starting point while
minimizing the overall travel distance or cost. Since TSP is NP-hard, no polynomial-time
solution is currently known. The Branch and Bound method offers a systematic approach to
solving TSP by breaking the problem down into smaller subproblems (branches) and
discarding those that cannot lead to a better solution than the best one found so far (bounding).
Pseudo code:
function TSP(graph, n):
Initialize min_cost = infinity
Initialize visited array of size n
Call branch_and_bound(graph, visited, 0, 0, 1, n, min_cost)
return min_cost
for i from 0 to n:
if visited[i] == false and graph[curr_pos][i] > 0:
visited[i] = true
branch_and_bound(graph, visited, i, cost + graph[curr_pos][i], level + 1, n, min_cost)
visited[i] = false
Code
#include <iostream>
#include <limits.h>
int main() {
int graph[MAX_NODES][MAX_NODES] = {
{0, 10, 15, 20},
{10, 0, 35, 25},
{15, 35, 0, 30},
{20, 25, 30, 0}
};
int n = 4;
cout << "Minimum cost of visiting all cities: " << TSP(graph, n) << endl;
return 0;
}
Output