forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
floyd_warshall.cpp
94 lines (90 loc) · 1.48 KB
/
floyd_warshall.cpp
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<bits/stdc++.h>
using namespace std;
void floyd_warshall(int arr[][5]) {
int i, j, k;
//Add all vertex one by one
for (k = 0; k < 5; k++) {
//pick all as a source
for (i = 0; i < 5; i++) {
//pick all as a destination
for (j = 0; j < 5; j++) {
if ((arr[i][k] * arr[k][j] != 0) && (i != j)) {
//If vertex k is on the shortest path from
// i to j, then update the value of arr[i][j]
if ((arr[i][k] + arr[k][j] < arr[i][j]) || (arr[i][j] == 0)) {
arr[i][j] = arr[i][k] + arr[k][j];
}
}
}
}
}
//function to print solution
cout << "\nOUTPUT" << endl;
for (i = 0; i < 5; i++) {
cout << "\nMinimum Cost for Node: " << i << endl;
for (j = 0; j < 5; j++) {
cout << arr[i][j] << "\t";
}
}
}
//Main function began
int main() {
int a[5][5];
//Enter values
cout << "Enter values for matrix-\n\n";
for (int i = 0; i < 5; i++) {
cout << "Enter values for " << (i + 1) << " row :" << endl;
for (int j = 0; j < 5; j++) {
cin >> a[i][j];
}
}
// call the floyd function
floyd_waeshall(a);
}
//main function ends
/*
Sample Input Output:
Enter values for matrix-
Enter values for 1 row :
0
3
6
0
0
Enter values for 2 row :
3
0
2
4
0
Enter values for 3 row :
6
2
0
1
4
Enter values for 4 row :
0
4
1
0
2
Enter values for 5 row :
0
0
4
2
0
OUTPUT:
Minimum Cost for Node: 0
0 3 5 6 8
Minimum Cost for Node: 1
3 0 2 3 5
Minimum Cost for Node: 2
5 2 0 1 3
Minimum Cost for Node: 3
6 3 1 0 2
Minimum Cost for Node: 4
8 5 3 2 0
Time Complexity :O(N^3)
*/