我暂时不去考虑超时的问题
- def solve(t_map)->int:
- s = []
- x,y = len(t_map),len(t_map[0])
- for l in range(x):
- if 'S' in t_map[l]:
- s = (l,t_map[l].index('S'))
- elif s:
- break
- d = ((-1,0),(1,0),(0,-1),(0,1))
- log = []
- def move(pos,n=0):
- if t_map[pos[0]][pos[1]] == 'T':
- return n
- log.append(pos)
- memory = []
- for de in d:
- np = (pos[0]+de[0],pos[1]+de[1])
- if (0<=np[0]<x and 0<=np[1]<y) and (np not in log) and t_map[np[0]][np[1]] != '#':
- memory.append(move(np,n+1))
- log.pop()
- return min(memory) if memory else int('f'*10,base=16)
- res = move(s)
- return -1 if res == int('f'*10,base=16) else res
- if __name__ == '__main__':
- print('示例1 2 输出:',solve([
- ['S', '.'],
- ['#', 'T']
- ]))
- print('别人错的 11# 2 输出:',solve([
- ['.', 'T', '.', 'S', '.', '#', '.', '.', '.', '.'],
- ['#', '.', '.', '.', '.', '#', '.', '#', '.', '.'],
- ['.', '.', '.', '.', '.', '.', '#', '.', '.', '#'],
- ['.', '.', '.', '.', '#', '#', '.', '.', '.', '.'],
- ['#', '#', '.', '.', '.', '.', '.', '#', '.', '#']]))
- print('别人错的 13# 21 输出:',solve([
- ['.', '#', '.', '.', '#', '.', '.', '.', '.', '#', '.', '#'],
- ['.', '.', '.', '.', '#', '.', '#', '.', '.', '.', '.', '.'],
- ['.', '.', '.', '.', '#', '#', '#', '#', '#', 'S', '.', '.'],
- ['#', '#', '.', '#', '.', '#', '.', '.', '#', '#', '.', '.'],
- ['.', '#', '.', '.', '.', '#', '#', '#', '.', '#', '#', '.'],
- ['.', '.', '#', '.', '.', '.', '.', '.', '.', '.', '.', '.'],
- ['.', '.', '#', '.', '#', '#', '#', '.', '.', '.', '.', '.'],
- ['.', '#', '.', '#', '#', '#', '.', '#', '.', '#', '.', '.'],
- ['#', '.', '.', '.', '#', '.', '.', '#', '.', '#', '#', '.'],
- ['.', '.', '#', '#', '#', '.', '#', '#', '.', '.', '.', '.'],
- ['#', '.', '#', '#', '.', '.', '#', '#', '#', '.', '#', '.'],
- ['.', '.', '.', '.', '.', '.', '.', '.', '#', '.', '#', '.'],
- ['#', '.', '.', '.', '#', '.', '#', '.', '.', '.', '#', '#'],
- ['#', '.', '#', '#', '#', 'T', '.', '#', '#', '.', '.', '#'],
- ['.', '#', '#', '#', '.', '#', '.', '.', '.', '#', '.', '.'],
- ['#', '.', '.', '.', '.', '#', '.', '#', '#', '.', '.', '.']]))
- print('别人错的 14# -1 输出:',solve([
- ['.', '#', '.', '#', '#', '.'],
- ['.', '#', 'S', '.', '#', '.'],
- ['.', '#', '.', '#', '#', '#'],
- ['.', '.', '#', '.', '#', '.'],
- ['.', '.', '.', '.', '.', '.'],
- ['.', '#', 'T', '.', '.', '.']]))
复制代码 |