forked from yesiamrajeev/Hacktoberfest2025
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamic_Programming.c++
More file actions
64 lines (47 loc) · 1.44 KB
/
Dynamic_Programming.c++
File metadata and controls
64 lines (47 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
Dynamic Programming idea:
Let dist[i][j] = shortest distance from vertex i to vertex j using only vertices 1..k as intermediate nodes.
Recurrence relation:
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
---
C++ Implementation
#include <iostream>
#include <vector>
using namespace std;
const int INF = 1e9; // Represents infinity
void floydWarshall(int n, vector<vector<int>>& graph) {
vector<vector<int>> dist = graph; // Copy initial graph
// Dynamic Programming steps
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] < INF && dist[k][j] < INF) // Avoid overflow
dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
}
}
}
// Print shortest distance matrix
cout << "Shortest distance matrix:\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 << "\n";
}
}
int main() {
int n;
cout << "Enter number of vertices: ";
cin >> n;
vector<vector<int>> graph(n, vector<int>(n));
cout << "Enter adjacency matrix (use 1e9 for INF):\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> graph[i][j];
}
}
floydWarshall(n, graph);
return 0;
}