LAB EXP LAST 5
LAB EXP LAST 5
LAB EXP LAST 5
#include <iostream>
#include <vector>
using namespace std;
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
#include <iostream>
#include <vector>
return true;
board[i][col] = 1;
return false;
int main() {
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.
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>
queue<int> q;
q.push(start);
visited[start] = true;
cout << "Nodes reachable from " << start << ": ";
while (!q.empty()) {
q.pop();
if (!visited[neighbor]) {
visited[neighbor] = true;
q.push(neighbor);
int main() {
int n = 5;
vector<vector<int>> adj = {
{1, 2},
{0, 3},
{0, 4},
{1},
{2}};
int start = 0;
return 0;
Output:
#include <iostream>
#include <vector>
visited[node] = true;
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;
A.Topological Sorting
#include <iostream>
#include <vector>
#include <stack>
visited[node] = true;
st.push(node);
stack<int> st;
while (!st.empty()) {
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
#include <iostream>
#include <vector>
for (int val : row) cout << val << " ";
}
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
#include <vector>
#include <climits>
minVertex = i;
return minVertex;
dist[src] = 0;
visited[u] = true;
for (int v = 0; v < n; v++) {
cout << "Shortest distances from vertex " << src << ":\n";
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},
int n = graph.size();
dijkstra(graph, 0, n);
return 0;
Output:
To 0: 0
To 1: 4
To 2: 12
To 3: 19
To 4: 21
To 5: 11