[[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标出来的目标点?
 grid = [[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]] def dfsSearch(x, y): if grid[x][y] == 2:
print('found at %d,%d' %(x, y))
return True
elif grid[x][y] == 1:
print('Wall at %d,%d' %(x, y))
elif grid[x][y] == 3:
print('Visited before: %d, %d' %(x, y))
return False print('Visiting %d,%d' %(x, y)) # mark as visited
grid[x][y] = 3 # explore neighbors clockwise starting by the one on the right
if ((x < len(grid) - 1) and dfsSearch(x + 1, y)) or \
(y > 0 and dfsSearch(x, y - 1)) or \
(x > 0 and dfsSearch(x - 1, y)) or \
((y < len(grid) - 1) and dfsSearch(x, y + 1)):
return True return False

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

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

 class findShortestPath(object):
def __init__(self):
self.minLen = [0x7FFFFFFF] def shortPath(self, x, y):
minLen = [999999]
self.shortPathHelper(x, y, 0)
return min(minLen) def shortPathHelper(self, x, y, step):
nextStep = [[0, 1], [1, 0], [0, -1], [-1, 0]]
if grid[x][y] == 2:
print('found at %d,%d' % (x, y))
self.minLen.append(step)
return True
elif grid[x][y] == 1:
print('Wall at %d,%d' % (x, y))
elif grid[x][y] == 3:
print('Visited before: %d, %d' % (x, y))
return False grid[x][y] = 3 for k in range(4):
tx = x + nextStep[k][0]
ty = y + nextStep[k][1] if (tx < 0 or tx > len(grid)-1 or ty < 0 or ty > len(grid)-1):
continue
self.shortPathHelper(tx, ty, step + 1)

最新文章

  1. How to create a Python dictionary with double quotes as default quote format?
  2. Ackerman函数的栈实现
  3. 在Linux中查看所有正在运行的进程
  4. {Latex}{Tabular}文本超出表格自动换行
  5. JCreator的配置
  6. 使用VIRTUALBOX安装ANDROID系统 | 图文教程 | 相关设置
  7. 15个让人惊讶的 CSS3 动画效果演示
  8. 【C++面试】常考题复习
  9. 包含中文的字符串中截取前N个字符
  10. 取消eclipse启动时的subclipse Usage弹窗
  11. Catch Application Exceptions in a Windows Forms Application
  12. 《C++ Primer Plus》学习笔记6
  13. Codeforces Round #248 (Div. 2) (ABCD解决问题的方法)
  14. 【2017集美大学1412软工实践_助教博客】个人作业3——个人总结(Alpha阶段)
  15. iOS支付宝,微信,银联支付集成封装调用(下)
  16. 【原创】大叔经验分享(47)yarn开启日志归集
  17. py001
  18. android ------- 开发者的 RxJava 详解
  19. Java数据解析---JSON
  20. 继承数组的slice方法

热门文章

  1. redis存在大量脏页问题的追查记录
  2. 事故记录:php-cgi进程过多导致系统资源耗尽
  3. 独立成分分析(ICA)在fMRI数据处理时timecourse的理解
  4. swift 随机生成背景颜色
  5. LeetCode 2. Add Two Numbers swift
  6. EntityFramework 启用迁移 Enable-Migrations 报异常 &quot;No context type was found in the assembly&quot;
  7. &quot;org.jboss.netty.internal.LoggerConfigurator&quot;.DESCRIBED is already registered 的解决办法
  8. Android 的图片异步请求加三级缓存 ACE
  9. 如何在 Apache 中为你的网站设置404页面
  10. WebService的两种方式SOAP和REST比较 (转)