2017阿里内推笔试题–算法工程师(运筹优化)
题目
沐哲是一个菜鸟仓库的一个拣货员,但他有非常个怪异的习惯。每次拣货的重量都要比之前拣的一个轻,每次拣到货后都可以得到1块钱,沐哲想知道这样最多能赚多少钱
32 34 7 33 21 2
13 12 3 11 26 36
16 30 22 1 24 14
20 23 25 5 19 29
27 15 9 17 31 4
6 18 8 10 35 28
沐哲可以从仓库的某个货架开始拣货,下一步可以往上走,也可以往下走,当然,向左向右也可以,但必须使得下一个货物重量减小,才会去拣。在上面的仓库中,一条可拣货的路径为 25-22-3。当然30-23-20-16-13-12-3可以拣的货更多。这也是赚钱最多的一条路径。
要求
输入行数、列数和数据矩阵,输出所赚的最大钱数。
例子:
输入:
6 6
32 34 7 33 21 2
13 12 3 11 26 36
16 30 22 1 24 14
20 23 25 5 19 29
27 15 9 17 31 4
6 18 8 10 35 28
输出:
7
分析
此题应该属于树搜索的题目,拿到题目后一直在想怎么用动态规划。结果测试时间都过了,还是没做出来,真是搓的一笔。
最暴力的解法就是对每个点遍历,以每个点为起点进行深度优先搜索,找它相邻点的可行路径。搜索后将最大结果保存到当前位置,等遍历完后,找到矩阵元素的最大值,然后输出该值。
版本一
函数:
# check the (i,j) is in the matrix index
def isInside(row,col,i,j):
return (i in range(row)) and (j in range(col))
# get the max step from the current point
def currentMaxStep(data,row,col,i,j):
max_step=0
directs = [(-1,0),(1,0),(0,-1),(0,1)]
for (dx,dy) in directs:
x,y = i+dx,j+dy
if(isInside(row,col,x,y) and data[x][y] < data[i][j]):
max_step = max([currentMaxStep(data,row,col,x,y),max_step])
return max_step + 1
# traverse the whole data and generate the max step map
def getMaxMap(data,row,col):
Map = [[0 for j in range(col)] for i in range(row)]
for i in range(row):
for j in range(col):
Map[i][j] = currentMaxStep(data,row,col,i,j)
print('the max step map is:')
for i in range(row):
print(Map[i])
return Map
# find the max from the max step map
def maxStep(data,row,col):
Map = getMaxMap(data,row,col)
return max([

1万+



被折叠的 条评论
为什么被折叠?



