京东笔试第3题
这个代码自己看不出来有什么问题,测试一个都不通过
def min_cost(N, matrix):
directions = [(0, 1), (1, 0), (-1,0)]
visited = set()
start = (0, 0)
end = (1, N-1)
total_cost = matrix[0][0]
i = 0
while start != end:
visited.add(start)
tmp_cost = {}
for direction in directions:
new_x = start[0] + direction[0]
new_y = start[1] + direction[1]
if 0 <= new_x < 2 and 0 <= new_y < N and (new_x, new_y) not in visited:
tmp_cost[(new_x, new_y)] = matrix[new_x][new_y]
if i % 2 == 1:
max_key = max(tmp_cost, key=tmp_cost.get)
max_value = tmp_cost[max_key]
total_cost += max_value
start = max_key
i += 1
else:
min_key = min(tmp_cost, key=tmp_cost.get)
min_value = tmp_cost[min_key]
total_cost += min_value
start = min_key
i += 1
return total_cost
def min_cost(N, matrix):
directions = [(0, 1), (1, 0), (-1,0)]
visited = set()
start = (0, 0)
end = (1, N-1)
total_cost = matrix[0][0]
i = 0
while start != end:
visited.add(start)
tmp_cost = {}
for direction in directions:
new_x = start[0] + direction[0]
new_y = start[1] + direction[1]
if 0 <= new_x < 2 and 0 <= new_y < N and (new_x, new_y) not in visited:
tmp_cost[(new_x, new_y)] = matrix[new_x][new_y]
if i % 2 == 1:
max_key = max(tmp_cost, key=tmp_cost.get)
max_value = tmp_cost[max_key]
total_cost += max_value
start = max_key
i += 1
else:
min_key = min(tmp_cost, key=tmp_cost.get)
min_value = tmp_cost[min_key]
total_cost += min_value
start = min_key
i += 1
return total_cost
全部评论
我样例过了,提交一个不过
老哥,第一手貌似是走到初始位置,这个我也最后看了用例才注意到,然后来不及了😰😰
相关推荐
点赞 评论 收藏
分享