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

问题:

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



                
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值