- Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMinSumMatrix.py
More file actions
Latest commit
36 lines (30 loc) · 1.04 KB
/
Copy pathMinSumMatrix.py
File metadata and controls
36 lines (30 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
importtime
matrix= [[1,2,3,4,4],[4,5,6,7,5],[7,8,9,10,5],[3,4,7,2,5],[3,4,7,2,10]]
# saves the minimum cost to reach each node on the matrix
minPathCache= [[None,None,None,None,None] for_inrange(5)]
# saves the best move to reach each node on the matrix
bestMoveCache= [[None,None,None,None,None] for_inrange(5)]
'''
get the minium sum of the path from (0,0) to (n,n) in the matrix
'''
defminPath(x,y):
ifminPathCache[x][y] isnotNone:
returnminPathCache[x][y]
else:
# all the previous places we could have come from
previous= []
ifx>0:
previous.append( (minPath(x-1, y), "U",) )
ify>0:
previous.append( (minPath(x, y-1), "L",) )
bestTuple=min(previous) ifpreviouselse (0, "*",)
minPathCache[x][y] =bestTuple[0] +matrix[x][y]
bestMoveCache[x][y] =bestTuple[1]
returnminPathCache[x][y]
start=time.time()
printstart
printminPath(4,4)
stop=time.time()
printstop
print"Elapsed: %.02f us"% ((stop-start) *1000000)
print"\n".join([str(row) forrowinbestMoveCache])