1. Recursive Multi-Source DFS
Intuition
Explore all 3 recursive branches from every cell in row 0 down to row N-1.
Algorithm
- Define helper
dfs(r, c). - If
c < 0 || c >= M, return -\infty. - If
r == 0, returnmat[0][c]. - Otherwise, return
mat[r][c] + max({ dfs(r-1, c-1), dfs(r-1, c), dfs(r-1, c+1) }). - Evaluate for all columns in row N-1 and take the max.
#include <iostream>#include <vector>#include <algorithm>#include <climits> using namespace std; class Solution { int dfs(int r, int c, const vector<vector<int>>& mat, int n, int m) { if (c < 0 || c >= m) return -1e9; if (r == 0) return mat[0][c]; int up = dfs(r - 1, c, mat, n, m); int upLeft = dfs(r - 1, c - 1, mat, n, m); int upRight = dfs(r - 1, c + 1, mat, n, m); return mat[r][c] + max({up, upLeft, upRight}); }public: int maximumPath(int n, int m, vector<vector<int>>& mat) { int maxVal = -1e9; for (int j = 0; j < m; ++j) { maxVal = max(maxVal, dfs(n - 1, j, mat, n, m)); } return maxVal; }}; int main() { Solution sol; vector<vector<int>> mat = { {1, 2, 10, 4}, {100, 3, 2, 1}, {1, 1, 20, 2}, {1, 2, 2, 1} }; cout << "Max Path Sum: " << sol.maximumPath(4, 4, mat) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(M * 3^N) - Space complexity:
O(N) call stack