From d1e2d4a9cf6eb830d521a94d0eb6e906b054e012 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 18 Jul 2022 17:40:53 +0000 Subject: [PATCH] problems: add out of boundary paths --- problems/out-of-boundary-paths.cpp | 62 ++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 problems/out-of-boundary-paths.cpp diff --git a/problems/out-of-boundary-paths.cpp b/problems/out-of-boundary-paths.cpp new file mode 100644 index 0000000..d731fd8 --- /dev/null +++ b/problems/out-of-boundary-paths.cpp @@ -0,0 +1,62 @@ +class Solution { +private: + const static unsigned CAP = 1000000007; + + class dp { + const int rows; + const int cols; + const int maxMove; + + std::vector>> paths; + + int + dfs(int y, int x, int moves) + { + 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> { + { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }) { + options = (options + dfs(y + dy, x + dx, moves - 1)) % CAP; + } + paths[y][x][moves] = options; + + return options; + } + + public: + dp(int rows, int cols, int maxMove) + : rows(rows) + , cols(cols) + , maxMove(maxMove) + , paths(rows, std::vector>(cols)) + { + } + + int + get(int row, int col) + { + return dfs(row, col, maxMove); + } + }; + +public: + int + findPaths(int m, int n, int maxMove, int startRow, int startColumn) const + { + return dp(m, n, maxMove).get(startRow, startColumn); + } +};