马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
[['SE', 'SW', 'NE', 'NW', 'NW', 'SE', 'NE'],
['NE', 'NE', 'NW', 'SW', 'NE', 'SE', 'SW'],
['SW', 'SE', 'NE', 'SW', 'SE', 'NE', 'SW'],
['SW', 'SE', 'SE', 'SW', 'SW', 'SW', 'NE'],
['SW', 'NW', 'SE', 'SE', 'SE', 'NW', 'SW'],
['NE', 'SW', 'NE', 'SW', 'SW', 'SE', 'NW'],
['NW', 'SW', 'NW', 'NW', 'SE', 'SE', 'SW']]
图片显示的是NE, NW, SE, SW可以走的方向,优先对角线,然后水平,然后垂直,
寻找从这个二维矩阵的中心(3,3)到四个角(0,0),(0,6),(6,0),(6,6)的最短路径,并输出最短路径,如果没有就不用写。
例如:
There is no path to (0, 0)
There is no path to (0,6)
The preferred path to (6, 6) is:
[(3, 3), (4,3), (4, 4), (5, 5), (6, 6)]
The preferred path to (6,0) is:
[(3, 3), (4,2), (5,3), (6,2), (5,1), (6,0)]
本帖最后由 claws0n 于 2018-10-6 06:15 编辑
- maze = [['SE', 'SW', 'NE', 'NW', 'NW', 'SE', 'NE'],
- ['NE', 'NE', 'NW', 'SW', 'NE', 'SE', 'SW'],
- ['SW', 'SE', 'NE', 'SW', 'SE', 'NE', 'SW'],
- ['SW', 'SE', 'SE', 'SW', 'SW', 'SW', 'NE'],
- ['SW', 'NW', 'SE', 'SE', 'SE', 'NW', 'SW'],
- ['NE', 'SW', 'NE', 'SW', 'SW', 'SE', 'NW'],
- ['NW', 'SW', 'NW', 'NW', 'SE', 'SE', 'SW']]
- def solveMaze(start, dest):
- paths = []
- r = len(maze)
- c = len(maze[0])
- limit = (abs(start[0]-dest[0]) + abs(start[1]-dest[1]))
- def solvingmaze(path, dest):
- nonlocal paths, r, c, limit
- if path[-1] == dest:
- paths.append(path[:])
- return
-
- x = path[-1][0]
- y = path[-1][1]
- if maze[x][y] == 'NE':
- route = [[-1,1], [0,1], [-1,0]]
- elif maze[x][y] == 'NW':
- route = [[-1,-1], [0,-1], [-1,0]]
- elif maze[x][y] == 'SE':
- route = [[1,1], [0,1], [1,0]]
- elif maze[x][y] == 'SW':
- route = [[1,-1], [0,-1], [1,0]]
-
- for each in route:
- node = (path[-1][0] + each[0], path[-1][1] + each[1])
- if -1 not in node and r != node[0] and c != node[1]:
- if len(path) > limit:
- return
- if node in path:
- break
- path.append(node)
- solvingmaze(path,dest)
- path.pop(-1)
-
- solvingmaze( [ (start[0], start[1]) ] , dest)
- if len(paths) > 1:
- m = r*c
- for each in paths:
- if m > len(each):
- m = len(each)
- i = paths.index(each)
- print('The preferred path to {} is:'.format(dest))
- print(paths[i])
- else:
- print('There is no path to {}'.format(dest))
- # main()
- solveMaze((3,3),(0,0))
- solveMaze((3,3),(0,6))
- solveMaze((3,3),(6,0))
- solveMaze((3,3),(6,6))
复制代码- There is no path to (0, 0)
- There is no path to (0, 6)
- The preferred path to (6, 0) is:
- [(3, 3), (4, 2), (5, 3), (6, 2), (5, 1), (6, 0)]
- The preferred path to (6, 6) is:
- [(3, 3), (4, 3), (4, 4), (5, 5), (6, 6)]
复制代码可以知道姐姐读哪一间吗?怎么那么恐怖?
|