-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmincostpathwithkedges.cpp
More file actions
67 lines (62 loc) · 1.46 KB
/
mincostpathwithkedges.cpp
File metadata and controls
67 lines (62 loc) · 1.46 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
64
65
66
67
#include <climits>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
#define V 4
#define INF INT_MAX
int countwalksRec(int g[][V], int u, int v, int k)
{
if (k == 0 && u == v) return 0;
if (k == 1 && g[u][v]) return g[u][v];
if (k <= 0) return INF;
int count = INF;
for (int i = 0; i < V; ++i)
{
int t = g[u][i];
if (t != INF && i != u && i != v)
{
count = std::min(count, t + countwalksRec(g, i, v, k - 1));
}
}
return count;
}
int countwalks(int g[][V], int u, int v, int k)
{
vector<vector<vector<int>>> dp(V, vector<vector<int>>(V, vector<int>(k+1)));
for (int edges = 0; edges <= k; ++edges)
{
for (int i = 0; i < V; ++i)
{
for (int j = 0; j < V; ++j)
{
dp[i][j][edges] = INF;
if (edges == 0 && i == j)
dp[i][j][edges] = g[i][j];
else if (edges == 1 && g[i][j])
dp[i][j][edges] = g[i][j];
else if (edges > 1) {
for (int t = 0; t < V; ++t)
{
if (g[i][t] != INF && t != i && dp[t][j][edges-1] != INF)
dp[i][j][edges] = std::min(dp[i][j][edges], g[i][t] + dp[t][j][edges-1]);
}
}
}
}
}
return dp[u][v][k];
}
int main()
{
/* Let us create the graph shown in above diagram*/
int graph[V][V] = { {0, 10, 3, 2},
{INF, 0, INF, 7},
{INF, INF, 0, 16},
{INF, INF, INF, 0}
};
int u = 0, v = 3, k = 2;
cout << countwalks(graph, u, v, k);
getchar();
return 0;
}