'Index Out of Rnage in finding ways for binary maze

Basically, I want to find the number of unique paths on the maze, but however, I've tried this code and it's working for my first matrix of the binary maze, however, it only identifies 1 unique path, however, the answer should be 2 because, on the maze[3][0], it could take a new unique path using the "right-down" choice rather than going to maze[4][0] and taking "right" choice.

# Check if cell (x, y) is valid or not

def isValidCell(x, y, N, M): return not (x < 0 or y < 0 or x >= N or y >= M)

def countPaths(maze, i, j, dest, visited):

# `N × M` matrix
N = len(maze)
M = len(maze[0])

# if destination (x, y) is found, return 1
if (i, j) == dest:
    return 1

# stores number of unique paths from source to destination
count = 0

# mark the current cell as visited
visited[i][j] = True

# if the current cell is a valid and open cell
if isValidCell(i, j, N, M) and maze[i][j] == 1:
    
    print(i)
    # go down (i, j) ——> (i + 1, j)
    if i + 1 < N and not visited[i + 1][j]:
        print("down")
        count += countPaths(maze, i + 1, j, dest, visited)
        
        # go up (i, j) ——> (i - 1, j)
    elif i - 1 >= 0 and not visited[i - 1][j]:
        print("up")
        count += countPaths(maze, i - 1, j, dest, visited)
        
        # go right (i, j) ——> (i, j + 1)
    elif j + 1 < M and not visited[i][j + 1]:
        print("right")
        count += countPaths(maze, i, j + 1, dest, visited)

    # go right-down (diagonal) (i, j) ——> (i + 1, j + 1)
    elif j + 1 < M and i + 1 < N and not visited[i + 1][j + 1]:
        print("right down")
        count += countPaths(maze, i + 1, j + 1, dest, visited)

    
# backtrack from the current cell and remove it from the current path
visited[i][j] = False

return count

def findCount(maze, src, dest):

# get source cell (i, j)
i, j = src

# get destination cell (x, y)
x, y = dest

# base case: invalid input
if not maze or not len(maze) or not maze[i][j] or not maze[x][y]:
    return 0

# `N × M` matrix
N = len(maze)
M = len(maze[0])

print(M)
# 2D matrix to keep track of cells involved in the current path
visited = [[False for k in range(M)] for l in range(N)]

# start from source cell (i, j)
return countPaths(maze, i, j, dest, visited)

if name == 'main':

maze = [
    [1, 0], 
    [1, 0], 
    [1, 0], 
    [1, 0], 
    [1, 1] 
]

# source cell
src = (0, 0)

# destination cell
dest = (4, 1)

print("The total number of unique paths are", findCount(maze, src, dest))


Solution 1:[1]

The code assumes a square matrix

# `N × N` matrix
N = len(maze)

You are feeding it a rectangular matrix maze = 15x5 (didn't count the lines, guesstimated)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gnight