python 题目一,给出一张数组map,输入起点和终点,找一通路
2016-03-30 23:07
585 查看
问题:
存在一张0,1数组的map,0:无障碍,1:障碍。
用户输入一个起点,和一个终点,寻找一条通路。
分析:
采用广度查找法。
第一次查找:蓝色表示,
第二次查找:红色表示,
按照这个方法来进行遍历循环,得到路径
代码如下:
存在一张0,1数组的map,0:无障碍,1:障碍。
用户输入一个起点,和一个终点,寻找一条通路。
分析:
采用广度查找法。
第一次查找:蓝色表示,
第二次查找:红色表示,
按照这个方法来进行遍历循环,得到路径
代码如下:
<pre name="code" class="python">#!/usr/bin/env python # -*- coding: utf-8 -*- ''' 这里有一张地图,0表示无障碍,可以通过, 1表示无法通过,需要绕路 输入一个起始点 (0,0) 输入一个终点(3,1) 寻找一条通路,从起始点到终点,一共需要多少步。 ''' map = [ [0,0,1,0], [0,0,0,0], [0,1,0,0], [1,0,0,0]] row = len(map) col = len(map[0]) fromX = 0 fromY = 0 endX = 3 endY = 1 print 'from direction(%d,%d)-->(%d,%d):' % (fromX,fromY,endX,endY) step = 0 direction = [(1,0), (0, 1), (-1, 0), (0, -1)] moveList = [] #目的标记做过了那些坐标。 newCanMoveList = [] #方便下次遍历是从那些坐标开始遍历。 newCanMoveList.append((fromX, fromY)) while fromX != endX and fromY != endY and len(newCanMoveList) > 0: prevMoveList = newCanMoveList newCanMoveList = [] step += 1 for xyItem in prevMoveList: if xyItem not in moveList: moveList.append(xyItem) for dItem in direction: chgx = xyItem[0] + dItem[0] chgy = xyItem[1] + dItem[1] #检查此时是否在地图的边缘, #检查是否已经走过,或者是障碍物。 if chgx < 0 or chgx >= row or chgy < 0 or chgy >= col : continue elif map[chgx][chgy] == 1 or (chgx,chgy) in moveList: continue elif chgx == endX and chgy == endY: fromX = chgx fromY = chgy break else: newCanMoveList.append((chgx, chgy)) moveList.append((chgx,chgy)) if fromX == endX and fromY == endY: break if fromX != endX and fromY != endY: print "it doesn't have the way from start to end." else: print 'it need step %d from start to end.' % step
相关文章推荐
- 深圳Python培训机构
- python中根据list中字符串元素的某一位(几位数字)对list排序
- Python学习,第一节
- python内置数据类型(数字和字符串)
- 学习Python (七)
- 学习Python (三)
- python学习之模块添加
- 【美妙的Python之二】Python初步
- Python 练习册,每天一个小程序
- python小例子之删除文本标签
- C++ 嵌入Python学习(一)
- 初级python学习记录
- 一个简单的备份脚本
- Python学习基础篇(一)
- python学习五 列表(list)、字典(dict)、字符串(string)
- python学习——python中命令行参数和os模块 推荐
- python 学习笔记(01)
- python 学习笔记(02)
- python 学习笔记(03)
- Python学习笔记:Python的常用内置函数1