Created
May 7, 2018 20:10
-
-
Save patelpreet422/5ef42f7bc8abf0bf0e2bcbe7dfd74332 to your computer and use it in GitHub Desktop.
Lattice path
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <map> | |
#include <iostream> | |
#include <algorithm> | |
unsigned long long moveto(const std::pair<int, int> &p, std::map< std::pair<int, int>, unsigned long long> &memo) | |
{ | |
if(memo.find(p) != memo.end()) return memo[p]; | |
/* | |
(0, 0) -> (0, 0) => We are already at our destiny so, no of ways we can reach our destiny is '0' | |
(0, 0) -> (a, 0) => Only '1' way to reach any point on X-axis from origin | |
(0, 0) -> (0, b) => Only '1' way to reach any point on Y-axis from origin | |
*/ | |
int x = p.first, y = p.second; | |
if(x == 0 && y == 0) return 0; | |
if(x == 0 && y != 0) return 1; | |
if(x != 0 && y == 0) return 1; | |
unsigned long long path; | |
path = moveto(std::pair<int, int>(x - 1, y), memo) + moveto(std::pair<int, int>(x, y - 1), memo); | |
memo[p] = path; | |
return path; | |
} | |
unsigned long long moveto(const std::pair<int, int> &p) | |
{ | |
std::map< std::pair<int, int>, unsigned long long> memo; | |
return moveto(p, memo); | |
} | |
int main() | |
{ | |
for(int i = 0; i <= 20; ++i) | |
{ | |
for(int j = 0; j <= 20; ++j) | |
{ | |
std::cout << "(" << i << ", " << j << "): " << moveto(std::pair<int, int>(i, j)) << '\n'; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment