Given a matrix like board I want to find the path that allows me to find more number 1's, knowing that I can only go up (n+1) and right (m+1). I'm trying to use a backtracking solution, and I managed to know how many 1's I can find on the best path but I'm having trouble figuring out how to print the coordinates of the best path.
board=[[0,0,0,0,1,0],
[0,1,0,1,0,0],
[0,0,0,1,0,1],
[0,0,1,0,0,1],
[1,0,0,0,1,0]]
def findPath(board,n,m):
noo=0
if board[n][m]>0:
noo+=1
if n==len(board)-1 and m==len(board[0])-1:
return noo
if n==len(board)-1:
noo+=findPath(board,n,m+1)
elif m==len(board[0])-1:
noo+=findPath(board,n+1,m)
else:
noo+=max(findPath(board,n,m+1),findPath(board,n+1,m))
return noo
print(findPath(board,0,0))
How or where should I implement the print(n,m) to print the coordinates of every grid of the best path
EDITED
Came up with this solution instead
def path(board,x,y,xl,yl,sol,index,paths):
sol.append([x,y])
solaux=sol
if x==0 and y==0:
pass
if board[x][y]>0:
sol[0]+=1
if x==xl-1 and y==yl-1:
paths.append(sol)
print(sol)
return paths
if x==xl-1:
path(board,x,y+1,len(board),len(board[0]),sol,index,paths)
elif y==yl-1:
path(board,x+1,y,len(board),len(board[0]),sol,index,paths)
else:
index= len(sol)
auxnoo= sol[0]
path(board,x,y+1,len(board),len(board[0]),sol,index,paths)
sol = sol[0:index]
sol[0]=auxnoo
path(board,x+1,y,len(board),len(board[0]),sol,index,paths)
return paths