DFS经典题,reachable or not in a 2D maze

 [[0, 0, 0, 0, 0, 1],
[1, 1, 0, 0, 0, 1],
[0, 0, 0, 1, 0, 0],
[0, 1, 1, 0, 0, 1],
[0, 1, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 2]]

给定类似上面个一个 m by n matrix。其中0代表可以走的路,1代表不能走的墙。任意给出起点坐标(i, j)判段是否能从起点走到用2标出来的目标点?


 1 grid = [[0, 0, 0, 0, 0, 1],
 2   [1, 1, 0, 0, 0, 1],
 3   [0, 0, 0, 1, 0, 0],
 4   [0, 1, 1, 0, 0, 1],
 5   [0, 1, 0, 0, 1, 0],
 6   [0, 1, 0, 0, 0, 2]]
 7 
 8 
 9 def dfsSearch(x, y):
10 
11     if grid[x][y] == 2:
12         print('found at %d,%d' %(x, y))
13         return True
14     elif grid[x][y] == 1:
15         print('Wall at %d,%d' %(x, y))
16     elif grid[x][y] == 3:
17         print('Visited before: %d, %d' %(x, y))
18         return False
19 
20     print('Visiting %d,%d' %(x, y))
21 
22     # mark as visited
23     grid[x][y] = 3
24 
25     # explore neighbors clockwise starting by the one on the right
26     if ((x < len(grid) - 1) and dfsSearch(x + 1, y)) or \
27             (y > 0 and dfsSearch(x, y - 1)) or \
28             (x > 0 and dfsSearch(x - 1, y)) or \
29             ((y < len(grid) - 1) and dfsSearch(x, y + 1)):
30         return True
31 
32     return False

这个算法只是检查能不能找到符合要求的path,但是不保证找到的那一条path是最短的。注意把已经访问过的点设置成3,这样访问过的点就不会被重复访问了。

 

如果想要找出shortest path的长度,可以用如下的方法:

 1 class findShortestPath(object):
 2     def __init__(self):
 3         self.minLen = [0x7FFFFFFF]
 4 
 5     def shortPath(self, x, y):
 6         minLen = [999999]
 7         self.shortPathHelper(x, y, 0)
 8         return min(minLen)
 9 
10     def shortPathHelper(self, x, y, step):
11         nextStep = [[0, 1], [1, 0], [0, -1], [-1, 0]]
12         if grid[x][y] == 2:
13             print('found at %d,%d' % (x, y))
14             self.minLen.append(step)
15             return True
16         elif grid[x][y] == 1:
17             print('Wall at %d,%d' % (x, y))
18         elif grid[x][y] == 3:
19             print('Visited before: %d, %d' % (x, y))
20             return False
21 
22 
23         grid[x][y] = 3
24 
25         for k in range(4):
26             tx = x + nextStep[k][0]
27             ty = y + nextStep[k][1]
28 
29             if (tx < 0 or tx > len(grid)-1 or ty < 0 or ty > len(grid)-1):
30                 continue
31             self.shortPathHelper(tx, ty, step + 1)

 

posted @ 2016-12-23 06:31  lettuan  阅读(188)  评论(0编辑  收藏  举报