您的位置:首页 > 编程语言 > Python开发

python 题目一,给出一张数组map,输入起点和终点,找一通路

2016-03-30 23:07 585 查看
问题:

存在一张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学习