VOOZH about

URL: https://www.geeksforgeeks.org/dsa/valid-paths-in-a-grid-in-python/

⇱ Valid paths in a grid in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Valid paths in a grid in Python

Last Updated : 23 Jul, 2025

Given a 2D grid of 0s (obstacles) and 1s (valid paths), find the number of valid paths from the top-left corner to the bottom-right corner. You can only move down or right.

Examples:

Input: grid = [ [1, 1, 1], [1, 0, 1], [1, 1, 1]]
Output: 2

Input: grid = [ [1, 1], [1, 1]]
Output: 1

Valid paths in a grid using Recursion:

Idea is to use a recursive approach to explore all possible paths from the starting cell to the ending cell and check if the unique and valid paths.

Steps to solve the problem:

  1. Start from the top-left cell (0, 0).
  2. Recursively explore two paths:
    • Move down from (i, j) to (i+1, j) if it's a valid path.
    • Move right from (i, j) to (i, j+1) if it's a valid path.
  3. If (i, j) reaches the bottom-right cell (m-1, n-1), increment the count of valid paths.

Below is the implementation of the approach:


Output
1
2

Time Complexity: O(2m+n) where m is the number of rows and n is the number of columns.
Auxiliary Space: O(m+n) for the recursion stack.

Valid paths in a grid using Dynamic Programming (DP):

Use a 2D dp array to store the number of valid paths to reach each cell in the grid. The DP approach is significantly more efficient than the naïve recursive approach because it avoids redundant computations by storing the solutions to subproblems in a 2D array.

Steps to solve this problem:

  1. Initialize a 2D dp array of the same size as the grid.
  2. Initialize the first row and first column of dp:
    • dp[i][0] = 1 if grid[i][0] == 1, else dp[i][0] = 0
    • dp[0][j] = 1 if grid[0][j] == 1, else dp[0][j] = 0
  3. For each cell (i, j) in the grid, update dp[i][j] as:
    • dp[i][j] = dp[i-1][j] + dp[i][j-1] if grid[i][j] == 1, else dp[i][j] = 0

Below is the implementation of the approach:


Output
1
2

Time Complexity: O(m×n) where m is the number of rows and n is the number of columns.
Auxiliary Space: O(m×n) for the creating dp array

Comment
Article Tags: