1. DFS Path Enumeration with Pruning
Intuition
Explore all simple paths from (0, 0) to (n - 1, n - 1). Track the maximum cell value along the path. Maintain an array minTime[r][c] to prune any path whose current peak elevation exceeds the recorded minimum for that cell.
Algorithm
- Initialize
minTimegrid of size n × n with infinity, setminTime[0][0] = grid[0][0]. - Define
dfs(r, c, currentMax): -
currentMax = max(currentMax, grid[r][c]) - If
currentMax >= minTime[r][c], return. -
minTime[r][c] = currentMax. - If
r == n - 1 && c == n - 1, return. - Explore 4 neighbors
(nr, nc)and recurse. - Return
minTime[n - 1][n - 1].
#include <iostream>#include <vector>#include <algorithm>#include <climits> const int dr[] = {-1, 1, 0, 0};const int dc[] = {0, 0, -1, 1}; void dfs(int r, int c, int currentMax, const std::vector<std::vector<int>>& grid, std::vector<std::vector<int>>& minTime) { currentMax = std::max(currentMax, grid[r][c]); if (currentMax >= minTime[r][c]) return; minTime[r][c] = currentMax; int n = grid.size(); if (r == n - 1 && c == n - 1) return; for (int d = 0; d < 4; ++d) { int nr = r + dr[d], nc = c + dc[d]; if (nr >= 0 && nr < n && nc >= 0 && nc < n) { dfs(nr, nc, currentMax, grid, minTime); } }} int swimInWaterDFS(std::vector<std::vector<int>>& grid) { int n = grid.size(); std::vector<std::vector<int>> minTime(n, std::vector<int>(n, INT_MAX)); dfs(0, 0, grid[0][0], grid, minTime); return minTime[n - 1][n - 1];} int main() { std::vector<std::vector<int>> grid = {{0, 2}, {1, 3}}; std::cout << "Swim in Water (DFS): " << swimInWaterDFS(grid) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(4^(N^2)) worst case without aggressive pruning. - Space complexity:
O(N^2) for the recursion stack and minTime grid.