華為機試43-迷宮問題(困難,五星)


題目描述
定義一個二維數組N*M(其中2<=N<=10;2<=M<=10),如5 × 5數組下所示:
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};

它表示一個迷宮,其中的1表示牆壁,0表示可以走的路,只能橫着走或豎着走,不能斜着走,要求編程序找出從左上角到右下角的最短路線。入口點為[0,0],既第一空格是可以走的路。

輸入描述:
一個N × M的二維數組,表示一個迷宮。數據保證有唯一解,不考慮有多解的情況,即迷宮只有一條通道。
輸入兩個整數,分別表示二位數組的行數,列數。再輸入相應的數組,其中的1表示牆壁,0表示可以走的路。數據保證有唯一解,不考慮有多解的情況,即迷宮只有一條通道。
輸出描述:
左上角到右下角的最短路徑,格式如樣例所示。

示例1
輸入
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

輸出
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)

 

參考1:

真正python 迷宮最短路徑解法

為何是真正?因為看了下別人的python 解法,都有個弊端,就是只能做從起點0到終點的唯一路徑的題,如果出現分支,或者多路徑求最短那么那些方法就不適用了。相對而言,以下做法不僅可以實現多路徑下的最短到終點探索,還能實現任意兩點之間的最短路徑返回,而且代碼還不長,符合python人生苦短特點,所以成為真!到最后面附原試題:
python是解簡單題最好用的方法

#利用動態規划和遞歸解
def jud(x,y,l,ll,lll):#求x,y點坐標在迷宮里的可能走法,即向上,向下,向左,向右
    n,m=len(l)-1,len(l[0])-1 #l為迷宮位置二維圖,ll為迷宮的每點從起點到該點
    k=[]     #的最短路徑,lll為記錄正在探索的從起點到該點的路線用以避免走重復
    if x+1<=n and (x+1,y) not in lll and l[x+1][y]!=1:k+=[(x+1,y)] 
    if x-1>=0 and (x-1,y) not in lll and l[x-1][y]!=1:k+=[(x-1,y)]
    if y+1<=m and (x,y+1) not in lll and l[x][y+1]!=1:k+=[(x,y+1)]
    if y-1>=0 and (x,y-1) not in lll and l[x][y]!=1:k+=[(x,y-1)]
    return k
def mg(x,y,l,ll,lll):#x,y為該點坐標,其余同上,探索x,y的走法 k=jud(x,y,l,ll,lll)#k為可能的走法 lll+=[(x,y)] #lll位置儲存 if len(k)>0: #是否為可走 for v in k: x1,y1=v if not ll[x1][y1] : #如果x1,y1位置 還沒有路徑信息,用x,y位置進 ll[x1][y1]=ll[x][y]+[(x1,y1)] #行更新 if len(ll[x1][y1])>=len(ll[x][y])+1: #如果x1,y1之前儲存的路徑#要長於從x,y的路徑到x1,y1的,則更新x1,y1路徑信息 ll[x1][y1]=ll[x][y]+[(x1,y1)] mg(x1,y1,l,ll,lll.copy()) #再對x1,y1 這點進行探索 return False while True: try: nn,mm=list(map(int,input().split())) l,ll,lll=[],[],[] for i in range(nn): l+=[list(map(int,input().split()))] for i in range(nn): ll.append([]) for j in range(mm): ll[i].append([]) ll[0][0]=[(0,0)] mg(0,0,l,ll,lll) # 設置起始點為(0,0),你也可以設為其他點為起始, for v in ll[-1][-1]: #來探索其他點到任意一點的最短位置 print("(%d,%d)"%(v[0],v[1])) #ll[-1][-1], 指的是將右下角一點設 except: break #為終點並打印出來,你也可以求其他點,如ll[2][3],來實現任意 #兩點求最短路

執行結果: 答案正確:恭喜!您提交的程序通過了所有的測試用例 用例通過率: 100.00% 運行時間: 18ms 占用內存: 3732KB

 

參考2:

廣度優先搜索

class MazeCracker():
    def __init__(self, row, column, matrix):
        self.row = row
        self.colum = column
        self.matrix = matrix
        self.result = [[0, 0]]
        self.current_x = 0
        self.current_y = 0
         
    def confict(self):     #判定當前位置是否為牆壁
        if self.matrix[self.current_x][self.current_y] == 1:
            return True
        return False
     
    def find_way(self):
        if self.current_x == self.row -1 and self.current_y == self.colum - 1:
            for i in self.result:
                print('({},{})'.format(*i))
            return
         
        for x, y in [[0, 1], [1, 0]]:  #兩輪x = 0, y = 1  和  x = 1, y = 0
            self.current_x += x
            self.current_y += y
            if self.current_x > self.row - 1 or self.current_y > self.colum - 1:
                self.current_x -= x
                self.current_y -= y
                continue
                 
            self.result.append([self.current_x, self.current_y])
            if not self.confict():    #判定當前位置是否為牆壁
                self.find_way()
            #否則退一步 
            self.result.pop()
            self.current_x -= x
            self.current_y -= y
 
def Main():
    while True:
        try:
            matrix_info = input()
            if matrix_info == '':
                break
            row, colum = list(map(int,matrix_info.split()))
             
            matrix = []
            for i in range(int(row)):
                matrix.append(list(map(int,input().split())))

            maze_instance = MazeCracker(int(row), int(colum), matrix)
            maze_instance.find_way()   #遞歸
        except:
            break 
 
if __name__=="__main__":
    Main()

執行結果: 答案正確:恭喜!您提交的程序通過了所有的測試用例 用例通過率: 100.00% 運行時間: 18ms 占用內存: 3468KB


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM