LeetCode/cpp/out-of-boundary-paths.cpp

52 lines
1.5 KiB
C++
Raw Permalink Normal View History

2022-07-18 19:40:53 +02:00
class Solution {
private:
2022-07-18 19:40:53 +02:00
const static unsigned CAP = 1000000007;
class dp {
const int rows;
const int cols;
const int maxMove;
std::vector<std::vector<std::map<int, unsigned>>> paths;
int dfs(int y, int x, int moves) {
2022-07-18 19:40:53 +02:00
if (y < 0 || y >= rows || x < 0 || x >= cols) {
// BASE: we got out of the bounds
return 1;
}
if (moves <= 0) {
// BASE: all moves were used or there are no moves left
return 0;
}
if (paths[y][x].count(moves)) {
// BASE(dynamic): already evaluated
return paths[y][x][moves];
}
int options = 0;
for (auto &[dx, dy] : std::vector<std::pair<int, int>>{
{0, 1}, {1, 0}, {0, -1}, {-1, 0}}) {
2022-07-18 19:40:53 +02:00
options = (options + dfs(y + dy, x + dx, moves - 1)) % CAP;
}
paths[y][x][moves] = options;
return options;
}
public:
2022-07-18 19:40:53 +02:00
dp(int rows, int cols, int maxMove)
: rows(rows), cols(cols), maxMove(maxMove),
paths(rows, std::vector<std::map<int, unsigned>>(cols)) {}
2022-07-18 19:40:53 +02:00
int get(int row, int col) { return dfs(row, col, maxMove); }
2022-07-18 19:40:53 +02:00
};
public:
int findPaths(int m, int n, int maxMove, int startRow,
int startColumn) const {
2022-07-18 19:40:53 +02:00
return dp(m, n, maxMove).get(startRow, startColumn);
}
};