MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / dfs

Function dfs

cpp/Graphs/longest_increasing_path.cpp:23–40  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

21}
22
23int 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
42bool isWithinBounds(int r, int c, std::vector<std::vector<int>>& matrix) {
43 return r >= 0 && r < matrix.size() && c >= 0 && c < matrix[0].size();

Callers 1

longestIncreasingPathFunction · 0.70

Calls 1

isWithinBoundsFunction · 0.70

Tested by

no test coverage detected