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
|
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
int countPaths(vector<vector<int>> const &mat, int m, int n, int cost,
unordered_map<string,int> &lookup)
{
if (cost < 0) {
return 0;
}
if (m == 0 && n == 0)
{
if (mat[0][0] - cost == 0) {
return 1;
}
else {
return 0;
}
}
string key = to_string(m) + "|" + to_string(n) + "|" + to_string(cost);
if (lookup.find(key) == lookup.end())
{
if (m == 0) {
lookup[key] = countPaths(mat, 0, n - 1, cost - mat[m][n], lookup);
}
else if (n == 0) {
lookup[key] = countPaths(mat, m - 1, 0, cost - mat[m][n], lookup);
}
else {
lookup[key] = countPaths(mat, m - 1, n, cost - mat[m][n], lookup) +
countPaths(mat, m, n - 1, cost - mat[m][n], lookup);
}
}
return lookup[key];
}
int countPaths(vector<vector<int>> const &mat, int cost)
{
if (mat.size() == 0) {
return 0;
}
int M = mat.size();
int N = mat[0].size();
unordered_map<string, int> lookup;
return countPaths(mat, M - 1, N - 1, cost, lookup);
}
int main()
{
vector<vector<int>> mat =
{
{ 4, 7, 1, 6 },
{ 5, 7, 3, 9 },
{ 3, 2, 1, 2 },
{ 7, 1, 6, 3 }
};
int cost = 25;
cout << "Total paths with cost " << cost << " are " << countPaths(mat, cost);
return 0;
}
| |