"""
Ref:算法竞赛入门经典(第二版)P57习题3-5
题目:有一个5*5的网格,其中恰好有一个格子是空的,其他格子各有一个字母。一共有4种指令:
A、B、L、R,分别表示把空格的上、下、左、右的相邻字母移到空格中。输入初始网格和
指令序列(以数字0结束),输出指令执行完毕后的网格。如果有非法指令,输出
"This puzzle has no final configuration",例如,图3-5执行ARRBBL0后,效果如图3-6.
"""
"""
:param net represents there are some characters lined in the 5th*5th net
:param command stands for the instructions to generate a new net
"""
def puzzle(net, command, valid_command_component):
#judge whether the command is valid or not
ct = 0
is_valid = 0
for le in range(0,len(command)-1):
if command[len(command)-1] == '0' and command[le] in valid_command_component:
ct += 1
if ct == len(command)-1:
is_valid = 1
if is_valid==0:
print("This puzzle has no final configuration")
if is_valid:
# find blank coordinates
coordinates_blank=(0,0)
for row in range(0,5):
for col in range(0,5):
if net[row][col] == None:
coordinates_blank = (row, col)
print(coordinates_blank)
row = coordinates_blank[0]
col = coordinates_blank[1]
for le in range(0, len(command)-1):
if command[le] == 'A':
if row == 0:
print("This puzzle has no final configuration")
else:
net[row][col] = net[row-1][col]
row = row - 1
coordinates_blank = (row, col)
if command[le] == 'B':
if row == 4:
print("This puzzle has no final configuration")
else:
net[row][col] = net[row+1][col]
row = row + 1
coordinates_blank = (row, col)
if command[le] == 'L':
if col == 0:
print("This puzzle has no final configuration")
else:
net[row][col] = net[row][col-1]
col = col - 1
coordinates_blank = (row, col)
if command[le] == 'R':
if col == 4:
print("This puzzle has no final configuration")
else:
net[row][col] = net[row][col+1]
col = col + 1
coordinates_blank = (row, col)
net[coordinates_blank[0]][coordinates_blank[1]] = None
return net
if __name__ == '__main__':
net = [['T','R','G','S','J'],['X','D','O','K','I'],['M',None,'V','L','N'],
['W','P','A','B','E'],['U','Q','H','C','F']]
command = 'ARRBBL0'
valid_command_component = ('A', 'B','L','R')
print(puzzle(net,command,valid_command_component))
算法竞赛入门经典(第二版)——第三章数组和字符串习题解答(二)3.5
最新推荐文章于 2020-09-16 21:16:16 发布