1. Recursive Multi-Source DFS
Intuition
Recursively branch into all 3 downward cells from every starting column in row 0.
Algorithm
- Define
solve(r, c). - If
c < 0 || c >= n, return \infty. - If
r == n - 1, returnmatrix[r][c]. - Return
matrix[r][c] + min({solve(r+1, c-1), solve(r+1, c), solve(r+1, c+1)}). - Evaluate for all
c in [0, n - 1]and return minimum.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { int solve(int r, int c, const vector<vector<int>>& mat, int n) { if (c < 0 || c >= n) return 1e9; if (r == n - 1) return mat[r][c]; int left = solve(r + 1, c - 1, mat, n); int down = solve(r + 1, c, mat, n); int right = solve(r + 1, c + 1, mat, n); return mat[r][c] + min({left, down, right}); }public: int minFallingPathSum(vector<vector<int>>& matrix) { int n = matrix.size(); int minSum = 1e9; for (int c = 0; c < n; ++c) { minSum = min(minSum, solve(0, c, matrix, n)); } return minSum; }}; int main() { Solution sol; vector<vector<int>> matrix = {{2, 1, 3}, {6, 5, 4}, {7, 8, 9}}; cout << "Min Falling Path: " << sol.minFallingPathSum(matrix) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(n * 3^n) - Space complexity:
O(n) call stack