我们需要找到到达每个地铁站花的最少的钱
这道题主要思路是递归,但是同一个站第一次坐两站只花两块钱增加了难度
代码在这里,主要递归就用一个函数shortest()完成了
我给这个4x4的sample二维数组赋值,按照上面的图让每个点等于这个站点需要花的钱
#use recursion to give each station a value
#sample是路线图, shortGraph是最便宜路线图
def shortest (sample, shortGraph,flag ,x ,y):
#如果越界,直接return
if x > 3 or x < 0 or y > 3 or y < 0:
return
#left 从左边到达这个点需要加的价格
left = 10
#up 从上面到达这个点需要加的价格
up = 10
#如果这个点左边无越界
if x - 1 >= 0:
#让到达左边的这个点的价格 加上 此时所在点的价格
left = shortGraph[y][x-1] + sample[y][x]
#如果这个点上面无越界
if y - 1 >= 0:
#同上
up = shortGraph[y-1][x] + sample[y][x]
#如果上面或者左边不是空
if x - 1 >=0 or y-1>=0:
#找到从左边和从右边来的价格比较低的那个
#flag 这个二维数组用来记录到达每个点时 是否连续跑了两个相同线路的站
if left <= up:
if flag[y][x-1] != sample[y][x] and sample[y][x]==sample[y][x-1]:
#如果是第一次连续到达两个同样的站点,只需要加2块钱
left = shortGraph[y][x-1] + 2
#让flag记录下来到达这个点时已经连续两个站点了
flag[y][x] = sample[y][x]
#如果连续跑三个同样站点
if flag[y][x-1] == sample[y][x] and sample[y][x]==sample[y][x-1]:
flag[y][x] = sample[y][x]
shortGraph[y][x] = left
else:
#从up来的,同上
if flag[y-1][x] != sample[y][x] and sample[y][x]==sample[y-1][x]:
up = shortGraph[y-1][x] + 2
flag[y][x] = sample[y][x]
if flag[y-1][x] == sample[y][x] and sample[y][x]==sample[y-1][x]:
flag[y][x] = sample[y][x]
shortGraph[y][x] = up
#最后访问这个点的右边和下面的点
shortest(sample, shortGraph, flag, x+1,y)
shortest(sample, shortGraph, flag, x,y+1)
#begin
#initialize the stations graph
stations = [[3 for i in range(4)] for i in range(4)]
for i in range(4):
stations[0][i] = 1
for i in range(1,4):
stations[1][i] = 4
for i in range(1,4):
stations[i][0] = 2
stations[3][1] = 2
flag = [[0 for i in range(4)] for i in range(4)]
short = [[0 for i in range(4)] for i in range(4)]
shortest(stations,short,flag,0,0)
#printout the least cost graph
print(short)
最后的结果是
0 | 2 | 3 | 4 |
2 | 6 | 7 | 8 |
4 | 7 | 9 | 11 |
6 | 8 | 11 | 13 |