0% found this document useful (0 votes)
28 views15 pages

Lab Exp Last 5

Chin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views15 pages

Lab Exp Last 5

Chin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

9.

Implement All-Pairs Shortest Paths Problem using Floyd's algorithm


 Purpose: Find the shortest paths between all pairs of nodes in a weighted graph.
 Steps:

1. Use dynamic programming to update distances between nodes.


2. Check if a path through an intermediate node is shorter.

 Time Complexity: O(n3)O(n^3)O(n3).

#include <iostream>
#include <vector>
using namespace std;

#define INF 99999

void floydWarshall(vector<vector<int>> &graph, int n) {


vector<vector<int>> dist = graph;

for (int k = 0; k < n; k++) {


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}

cout << "Shortest distances between every pair of vertices:\n";


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (dist[i][j] == INF) cout << "INF ";
else cout << dist[i][j] << " ";
}
cout << endl;
}
}

int main() {
vector<vector<int>> graph = {
{0, 3, INF, INF},
{2, 0, INF, INF},
{INF, 7, 0, 1},
{6, INF, INF, 0}};
int n = graph.size();

floydWarshall(graph, n);
return 0;
}

Output:
Shortest distances between every pair of vertices:
0 3 INF INF
2 0 INF INF
INF 7 0 1
6 9 INF 0

10. Implement N Queen's problem using Back Tracking.


 Purpose: Place NNN queens on an N×NN \times NN×N chessboard so that no two
queens attack each other.
 Steps:
1. Use backtracking to place queens one by one.
2. Check if the placement is safe (row, column, diagonals).
 Applications: Problem-solving, recursion concepts.

#include <iostream>

#include <vector>

using namespace std;

bool isSafe(vector<vector<int>> &board, int row, int col, int n) {

for (int i = 0; i < col; i++)

if (board[row][i]) return false;

for (int i = row, j = col; i >= 0 && j >= 0; i--, j--)

if (board[i][j]) return false;

for (int i = row, j = col; i < n && j >= 0; i++, j--)

if (board[i][j]) return false;

return true;

bool solveNQueens(vector<vector<int>> &board, int col, int n) {

if (col >= n) return true;

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

if (isSafe(board, i, col, n)) {

board[i][col] = 1;

if (solveNQueens(board, col + 1, n)) return true;


board[i][col] = 0; // backtrack

return false;

void printSolution(vector<vector<int>> &board, int n) {

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

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

cout << (board[i][j] ? "Q " : ". ");

cout << endl;

int main() {

int n = 4; // Example for 4-queens

vector<vector<int>> board(n, vector<int>(n, 0));

if (solveNQueens(board, 0, n)) printSolution(board, n);

else cout << "No solution exists.\n";

return 0;

}
Output:

.Q..

...Q

Q...

..Q.

7 a. Print all the nodes reachable from a given starting node in a digraph
usingBFS method. b. Check whether a given graph is connected or not using
DFSmethod.

A. BFS (Breadth-First Search)

 Purpose: Traverse a graph level by level and find reachable nodes from a starting node.
 Steps:
1. Use a queue to process nodes.
2. Mark visited nodes to avoid cycles.
 Time Complexity: O(V+E)O(V + E)O(V+E), where VVV is vertices and EEE is edges.

#include <iostream>

#include <vector>

#include <queue>

using namespace std;

void BFS(vector<vector<int>> &adj, int start, int n) {

vector<bool> visited(n, false);

queue<int> q;

q.push(start);

visited[start] = true;
cout << "Nodes reachable from " << start << ": ";

while (!q.empty()) {

int node = q.front();

q.pop();

cout << node << " ";

for (int neighbor : adj[node]) {

if (!visited[neighbor]) {

visited[neighbor] = true;

q.push(neighbor);

cout << endl;

int main() {

int n = 5;

vector<vector<int>> adj = {

{1, 2},

{0, 3},

{0, 4},

{1},

{2}};
int start = 0;

BFS(adj, start, n);

return 0;

Output:

Nodes reachable from 0: 0 1 2 3 4

B. DFS (Depth-First Search)

 Purpose: Check if a graph is connected by exploring as far as possible along each


branch.
 Steps:
1. Use recursion or a stack to explore neighbors.
2. Track visited nodes to detect connectivity.
 Time Complexity: O(V+E)O(V + E)O(V+E).

#include <iostream>

#include <vector>

using namespace std;

void DFS(vector<vector<int>> &adj, vector<bool> &visited, int node) {

visited[node] = true;

for (int neighbor : adj[node]) {

if (!visited[neighbor]) DFS(adj, visited, neighbor);

bool isConnected(vector<vector<int>> &adj, int n) {


vector<bool> visited(n, false);

DFS(adj, visited, 0);

for (bool v : visited)

if (!v) return false;

return true;

int main() {

int n = 4;

vector<vector<int>> adj = {

{1, 2},

{0, 3},

{0},

{1}};

cout << (isConnected(adj, n) ? "Graph is connected" : "Graph is not connected") << endl;

return 0;

Output: Graph is connected

3 a. Obtain the Topological ordering of vertices in a given digraph. b.


Computethe transitive closure of a given directed graph using Warshall's
algorithm.

A.Topological Sorting

 Purpose: Linear ordering of vertices in a Directed Acyclic Graph (DAG).


 Steps:
1. Use DFS to finish processing nodes.
2. Push nodes to a stack in reverse order of completion.
 Applications: Task scheduling, dependency resolution.
 Time Complexity: O(V+E)O(V + E)O(V+E).

#include <iostream>

#include <vector>

#include <stack>

using namespace std;

void topologicalSortUtil(vector<vector<int>> &adj, vector<bool> &visited, stack<int> &st, int


node) {

visited[node] = true;

for (int neighbor : adj[node])

if (!visited[neighbor]) topologicalSortUtil(adj, visited, st, neighbor);

st.push(node);

void topologicalSort(vector<vector<int>> &adj, int n) {

vector<bool> visited(n, false);

stack<int> st;

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

if (!visited[i]) topologicalSortUtil(adj, visited, st, i);

cout << "Topological Order: ";

while (!st.empty()) {

cout << st.top() << " ";


st.pop();

cout << endl;

int main() {

int n = 6;

vector<vector<int>> adj = {

{2, 3},

{3, 4},

{},

{5},

{5},

{}};

topologicalSort(adj, n);

return 0;

Output:

Topological Order: 1 4 0 2 3 5

B. Warshall’s Algorithm (Transitive Closure)

 Purpose: Determine reachability between nodes in a directed graph.


 Steps:
1. Use a boolean adjacency matrix.
2. Update reachability using intermediate nodes.
 Time Complexity: O(n3)O(n^3)O(n3).

#include <iostream>

#include <vector>

using namespace std;

void warshall(vector<vector<int>> &graph, int n) {

vector<vector<int>> reach = graph;

for (int k = 0; k < n; k++) {

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

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

reach[i][j] = reach[i][j] || (reach[i][k] && reach[k][j]);

cout << "Transitive Closure:\n";

for (const auto &row : reach) {

for (int val : row) cout << val << " ";

cout << endl;

}
int main() {

vector<vector<int>> graph = {

{1, 1, 0, 0},

{0, 1, 1, 0},

{0, 0, 1, 1},

{0, 0, 0, 1}};

int n = graph.size();

warshall(graph, n);

return 0;

Output:

Transitive Closure:

1111

0111

0011

0 001

5.From a given vertex in a weighted connected graph, find shortest paths


toother vertices using Dijkstra's algorithm.Purpose: Find the shortest path
from a source node to all other nodes in a weighted graph.
 Steps:
1. Use a priority queue or find the minimum distance node.
2. Update distances to neighboring nodes.
 Time Complexity: O(V2)O(V^2)O(V2) (with simple arrays), O(V+Elog⁡V)O(V + E \log
V)O(V+ElogV) (with priority queue).
#include <iostream>

#include <vector>

#include <climits>

using namespace std;

int findMinVertex(vector<int> &dist, vector<bool> &visited, int n) {

int minVertex = -1;

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

if (!visited[i] && (minVertex == -1 || dist[i] < dist[minVertex]))

minVertex = i;

return minVertex;

void dijkstra(vector<vector<int>> &graph, int src, int n) {

vector<int> dist(n, INT_MAX);

vector<bool> visited(n, false);

dist[src] = 0;

for (int i = 0; i < n - 1; i++) {

int u = findMinVertex(dist, visited, n);

visited[u] = true;
for (int v = 0; v < n; v++) {

if (graph[u][v] && !visited[v] && dist[u] + graph[u][v] < dist[v]) {

dist[v] = dist[u] + graph[u][v];

cout << "Shortest distances from vertex " << src << ":\n";

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

cout << "To " << i << ": " << dist[i] << endl;

int main() {

vector<vector<int>> graph = {

{0, 4, 0, 0, 0, 0},

{4, 0, 8, 0, 0, 0},

{0, 8, 0, 7, 0, 4},

{0, 0, 7, 0, 9, 14},

{0, 0, 0, 9, 0, 10},

{0, 0, 4, 14, 10, 0}};

int n = graph.size();

dijkstra(graph, 0, n);
return 0;

Output:

Shortest distances from vertex 0:

To 0: 0

To 1: 4

To 2: 12

To 3: 19

To 4: 21

To 5: 11

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy