Issue
I need a help on below image I want to achieve below logic in Python and I am newbie in Python.
[![I need a help on below image I want to achieve below logic in Python and I am newbie in Python.][1]][1]
Any help is appreciated.
Solution
I would suggest to seek for every possible path. An example from link then to compute every possible sums and look for the smallest
import numpy as np
import copy
def findPaths(mat, path,paths, i, j):
# base case
if not mat or not len(mat):
return
(M, N) = (len(mat), len(mat[0]))
# if the last cell is reached, print the route
if i == M - 1 and j == N - 1:
paths.append(copy.deepcopy(path + [[i,j]] ))
return
# include the current cell in the path
path.append( [i,j])
# move right
if 0 <= i < M and 0 <= j + 1 < N:
findPaths(mat, path,paths, i, j + 1)
# move down
if 0 <= i + 1 < M and 0 <= j < N:
findPaths(mat, path,paths, i + 1, j)
# backtrack: remove the current cell from the path
path.pop()
if __name__ == '__main__':
mat = [ [2,5,4],
[3,2,1],
[8,0,3] ]
path = []
paths = []
x = y = 0
#find all possible paths
findPaths(mat, path,paths, x, y)
print(paths)
#get the sum of all paths
All_sums = []
for path in paths:
one_sum = 0
for p in path:
one_sum += mat[p[0]][p[1]]
All_sums.append(one_sum)
print(All_sums)
#get lower path
min_path = np.argmin(All_sums)
print(min_path)
#print the path
print(paths[min_path])
#print the val sequence
print([mat[p[0]][p[1]] for p in paths[min_path]])
Answered By - ymmx
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.