Profile DP Grid Paths - Problem

You are given an m x n grid where some cells may contain obstacles. You start at the top-left corner (0, 0) and want to reach the bottom-right corner (m-1, n-1).

You can only move right or down at any point in time. An obstacle is represented by 1 and an empty cell is represented by 0.

Count the number of unique paths from the start to the destination. This problem extends to broken profiles where certain row configurations may be invalid due to obstacles creating disconnected regions.

Use Profile Dynamic Programming with bitmasks to efficiently track valid row states and transitions between adjacent rows.

Input & Output

Example 1 — Basic Grid with Obstacle
$ Input: grid = [[0,0,0],[0,1,0],[0,0,0]]
Output: 2
💡 Note: Two paths: (0,0)→(0,1)→(0,2)→(1,2)→(2,2) and (0,0)→(1,0)→(2,0)→(2,1)→(2,2). Cannot go through the obstacle at (1,1).
Example 2 — Path Blocked
$ Input: grid = [[0,1],[1,0]]
Output: 0
💡 Note: No valid path exists. Starting at (0,0), we cannot move right due to obstacle at (0,1) and cannot move down due to obstacle at (1,0).
Example 3 — No Obstacles
$ Input: grid = [[0,0],[0,0]]
Output: 2
💡 Note: Two paths: (0,0)→(0,1)→(1,1) and (0,0)→(1,0)→(1,1). Classic grid path counting without obstacles.

Constraints

  • 1 ≤ m, n ≤ 100
  • grid[i][j] is 0 or 1
  • grid[0][0] = grid[m-1][n-1] = 0

Visualization

Tap to expand
INPUTALGORITHMRESULT3×3 Grid with ObstaclesS0001000EStart: (0,0), End: (2,2)Obstacle at (1,1)1Initialize DP table2Fill table: dp[i][j] = dp[i-1][j] + dp[i][j-1]3Skip obstacles (set to 0)4Return dp[m-1][n-1]Dynamic ProgrammingTime: O(m×n), Space: O(m×n)2Unique PathsPath 1: (0,0)→(0,1)→(0,2)→(1,2)→(2,2)Path 2: (0,0)→(1,0)→(2,0)→(2,1)→(2,2)Both paths avoid the obstacleKey Insight:Use dynamic programming to build path counts incrementally, treating obstacles as barriers that reset the count to zero while maintaining optimal substructure.TutorialsPoint - Profile DP Grid Paths | 2D Dynamic Programming
Asked in
Google 42 Amazon 38 Microsoft 31 Facebook 29
78.0K Views
High Frequency
~35 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen