Unique paths II

Dynamic Programming DP on grids Medium
  • The underlying concept of this problem is extensively used in navigation and mapping services like Google Maps and GPS devices
  • Algorithms that solve similar pathfinding problems, like the A* algorithm, are designed to calculate the shortest route between two points
  • They consider obstacles (like blocked roads or traffic) by using a similar concept as the "1s" in the provided problem
  • Essentially, these algorithms navigate through a complex 2D grid very similar to this problem's matrix, but on a much larger and intricate scale

Given an m x n 2d array named matrix, where each cell is either 0 or 1. Return the number of unique ways to go from the top-left cell (matrix[0][0]) to the bottom-right cell (matrix[m-1][n-1]). A cell is blocked if its value is 1, and no path is possible through that cell.


Movement is allowed in only two directions from a cell - right and bottom.

Examples:

Input: matrix = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]

Output: 2

Explanation: The two possible paths are:

1) down -> down-> right -> right

2) right -> right -> down -> down

Input: matrix = [[0, 0, 0], [0, 0, 1], [0, 1, 0]]

Output: 0

Explanation: There is no way to reach the bottom-right cell.

Input: matrix = [[0, 0, 0, 0], [0, 0, 1, 0]]

Constraints

  • m == number of rows in matrix
  • n == number of columns in matrix
  • 1 <= n, m <= 100
  • Value of each cell in matrix is either 0 or 1
  • The answer will not exceed 109

Hints

  • "Let dp[i][j] represent the number of ways to reach cell (i, j). If matrix[i][j] == 1, the cell is blocked, so dp[i][j] = 0."
  • "A recursive approach without memoization results in exponential time complexity (O(2^{m+n})), making it inefficient for large grids. Using dynamic programming (O(m*n)), we store computed results in dp[][] to avoid redundant calculations."

Company Tags

Square Siemens Healthineers Intel Red Hat DoorDash Alibaba Johnson & Johnson JPMorgan Chase Swiggy Docker Ernst & Young Visa Pinterest Airbnb IBM ARM GE Healthcare Byju's Splunk Mastercard Western Digital Target Epic Games Bungie Robinhood Google Microsoft Amazon Meta Apple Netflix Adobe