"""2D array of characters1 1 1 1 1S 1 X 1 11 1 1 1 1X 1 1 E 11 1 1 1 XS is the starting pointE is the ending pointX means you cannot traverse to that point1. Find if there is a path from S to E2. Find the length of shortest path from S to E given the above matrix3. Find the shortest path from S to E given the above matrixRestriction: Move to 8 positions"""def find_path(map):M = len(map)N = len(map[0])S = Nonefor i in range(M):if S:breakfor j in range(N):if map[i][j] == 'S':S = (i, j)breakqueue = [ ( S, [] ) ]while len(queue) > 0:current, path = queue.pop()x, y = currentif x < 0 or y < 0 or x >= M or y >= N or map[x][y] == 'X':continuepath.append(current)if map[x][y] == 'E':return path # Or len(path) for question 2map[x][y] = 'X' # Mark as visitedqueue.insert(0, ((x-1, y-1), path[:]))queue.insert(0, ((x-1, y ), path[:]))queue.insert(0, ((x-1, y+1), path[:]))queue.insert(0, ((x , y-1), path[:]))queue.insert(0, ((x , y+1), path[:]))queue.insert(0, ((x+1, y-1), path[:]))queue.insert(0, ((x+1, y ), path[:]))queue.insert(0, ((x+1, y+1), path[:]))return Nonemap = [ ['1', '1', '1', '1', '1',],['S', '1', 'X', '1', '1',],['1', '1', '1', '1', '1',],['X', '1', '1', 'E', '1',],['1', '1', '1', '1', 'X',],]print find_path(map)# 讨论# 1. 无论用何种方法,最好的复杂度应该都是O(m*n)因为最坏情况都是要遍历完整个图# 2. 但是单就最好情况来说,想讨论下有没有更好的方法,主要考虑如下:# 因为实际已知 S 和 E 的坐标,这里用到的BFS实际是和不知道终点位置是一样的,都是BFS最先的情况就是答案# 但我觉得方法应该是可以向着终点方向走,遇到障碍让开走,如果能够实现这种方法,肯定是最优的解法,# 希望大家能给我点思路
Blog Archive
-
▼
2014
(190)
-
▼
October
(11)
- 封面论文会获得更高的关注度和更大的影响力吗? - 微科普 - 数字化科普知识平台
- Pool services, Pool service company, Pool Maintena...
- The Most Common Jobs For The Rich, Middle Class An...
- The Most Common Jobs For The Rich, Middle Class An...
- Top Coder算法题目浏览器 - Lucida
- Microsoft to close Microsoft Research lab in Silic...
- 前盛大高管的创业冒险:云知声创始人从幕后走向台前_科技_腾讯网
- Perseverance Quotes and Proverbs
- ABOUT -- Faculty Fellowship Summer Institute in Is...
- maze
- Find Shortest Path With Obstacle MAZE
-
▼
October
(11)
Thursday, October 2, 2014
Find Shortest Path With Obstacle MAZE
Find Shortest Path With Obstacle:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment