Link:
https://leetcode.com/problems/out-of-boundary-paths/
My Code:
class Solution:
def findPaths(self, m: int, n: int, N: int, i: int, j: int) -> int:
Total = 0
NumberMat = []
for k in range(m):
NumberMat.append([0]*n)
NumberMat[i][j] = 1
if m !=1 and n!=1:
for k in range(N):
for row in range(m):
if row == 0:
Total += sum(NumberMat[row])+NumberMat[row][0] + NumberMat[row][-1]
elif row == (m-1):
Total += sum(NumberMat[row])+NumberMat[row][0] + NumberMat[row][-1]
else:
Total =Total + NumberMat[row][0] + NumberMat[row][-1]
NewMat = []
for row in range(m):
NewList = []
for col in range(n):
if row == 0:
if col == 0:
NewValue = NumberMat[row+1][col]+NumberMat[row][col+1]
NewList.append(NewValue)
elif col == (n-1):
NewValue = NumberMat[row+1][col]+NumberMat[row][col-1]
NewList.append(NewValue)
else:
NewValue = NumberMat[row+1][col]+NumberMat[row][col-1]+NumberMat[row][col+1]
NewList.append(NewValue)
elif row == (m-1):
if col == 0:
NewValue = NumberMat[row-1][col]+NumberMat[row][col+1]
NewList.append(NewValue)
elif col == (n-1):
NewValue = NumberMat[row-1][col]+NumberMat[row][col-1]
NewList.append(NewValue)
else:
NewValue = NumberMat[row-1][col]+NumberMat[row][col-1]+NumberMat[row][col+1]
NewList.append(NewValue)
else:
if col == 0:
NewValue = NumberMat[row+1][col]+NumberMat[row][col+1]+NumberMat[row-1][col]
NewList.append(NewValue)
elif col == (n-1):
NewValue = NumberMat[row+1][col]+NumberMat[row][col-1]+NumberMat[row-1][col]
NewList.append(NewValue)
else:
NewValue = NumberMat[row+1][col]+NumberMat[row][col-1]+NumberMat[row][col+1]+NumberMat[row-1][col]
NewList.append(NewValue)
NewMat.append(NewList)
NumberMat = NewMat
return Total%(10**9+7)
elif m ==1 and n!=1:
for k in range(N):
Total += 2*sum(NumberMat[0])+NumberMat[0][0] + NumberMat[0][-1]
NewMat = []
NewList = []
for col in range(n):
if col == 0:
NewValue = NumberMat[0][col+1]
NewList.append(NewValue)
elif col == (n-1):
Explanation:
The DP array is defined as the number of paths that can reach ith row , jth col in the kth step. Then we just need to iterate with the number k until n-1. For each entry of the matrix, there are three situations: in the corner, on the side and others. For either case, we take the sum of all cells next to it as the value at that cell. For each time, we sum the possible out path( all value of cells on the boarder). Then we return the result of the total value.