| 21 | } |
| 22 | |
| 23 | int dfs(int r, int c, std::vector<std::vector<int>>& matrix, std::vector<std::vector<int>>& memo) { |
| 24 | if (memo[r][c] != 0) { |
| 25 | return memo[r][c]; |
| 26 | } |
| 27 | int maxPath = 1; |
| 28 | std::vector<std::pair<int, int>> dirs = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} }; |
| 29 | // The longest path starting at the current cell is equal to the |
| 30 | // longest path of its larger neighboring cells, plus 1. |
| 31 | for (auto& d : dirs) { |
| 32 | int nextR = r + d.first; |
| 33 | int nextC = c + d.second; |
| 34 | if (isWithinBounds(nextR, nextC, matrix) && matrix[nextR][nextC] > matrix[r][c]) { |
| 35 | maxPath = std::max(maxPath, 1 + dfs(nextR, nextC, matrix, memo)); |
| 36 | } |
| 37 | } |
| 38 | memo[r][c] = maxPath; |
| 39 | return maxPath; |
| 40 | } |
| 41 | |
| 42 | bool isWithinBounds(int r, int c, std::vector<std::vector<int>>& matrix) { |
| 43 | return r >= 0 && r < matrix.size() && c >= 0 && c < matrix[0].size(); |
no test coverage detected