京东笔试第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
全部评论
我样例过了,提交一个不过
老哥,第一手貌似是走到初始位置,这个我也最后看了用例才注意到,然后来不及了😰😰
相关推荐
点赞 评论 收藏
分享
艾莉Alliy:+1,这场题面确实太💩了,提问功能还是摆设,问什么都只会回答“这是考试,独立作答”。那这提问是摆设吗?这两个题我都按两个不同的题意写了两份代码才成功通过

点赞 评论 收藏
分享
09-24 10:31
重庆理工大学 算法工程师 
点赞 评论 收藏
分享
09-21 14:37
福建农林大学 Java 点赞 评论 收藏
分享