Skip to content

Instantly share code, notes, and snippets.

Created February 14, 2014 08:48
Show Gist options
  • Save anonymous/8997801 to your computer and use it in GitHub Desktop.
Save anonymous/8997801 to your computer and use it in GitHub Desktop.
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there?
class Solution {
public:
int uniquePaths(int m, int n) {
int pathCount[m][n];
memset(pathCount, 0, sizeof(pathCount));
pathCount[m - 1][n - 1] = 1;
for (int i = n - 1; i >= 0; i--) { // col
for (int j = m - 1; j >= 0; j--) { // row
if (j + 1 < m) { // to the right
pathCount[j][i] += pathCount[j + 1][i];
}
if (i + 1 < n) { // to the bottom
pathCount[j][i] += pathCount[j][i + 1];
}
}
}
return pathCount[0][0];
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment