迷宮最短路徑 深度優先搜尋—C—python__python

來源:互聯網
上載者:User

從迷宮的起點到終點的最短路徑,用深度優先搜尋

C實現

#include<stdio.h>int n,m,p,q,min=99999999;int a[100][100],book[100][100];void dfs(int x,int y,int step){    int tx,ty,k ;    int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}};    if(x==p&&y==q)    {        if(min>step)            min=step;        return;    }    for(k=0;k<=3;k++)    {       tx=x+next[k][0];       ty=y+next[k][1];       if(tx<1||tx>n||ty<1||ty>m)           continue;       if(a[tx][ty]==0&&book[tx][ty]==0)       {           book[tx][ty]=1;           dfs(tx,ty,step+1);           book[tx][ty]=0;       }    }    return;}int main(){    int i,j,startx,starty;    scanf("%d%d",&n,&m);    for(i=1;i<=n;i++)        for(j=1;j<=m;j++)        {            scanf("%d",&a[i][j]);        }    scanf("%d%d%d%d",&startx,&starty,&p,&q);    book[startx][starty]=1;    dfs(startx,starty,0);//步數也帶上作為參數    //輸出最短步數    printf("%d",min);    return 0;}

python 實現

def dfs(x,y,step):    global min    global tx,ty    next = [[0, 1], [1, 0], [0, -1], [-1, 0]]    if x == mx and y== my:        if min > step:            min = step            print(min)        return    for k in range(4):        tx = x + next[k][0]        ty = y + next[k][1]        if tx < 0 or tx > n-1 or ty < 0 or ty > m-1:            continue        if a[tx][ty]==0 and book[tx][ty]==0:            book[tx][ty]=1            dfs(tx,ty,step+1)            book[tx][ty]=0    returnif __name__=='__main__':    n=int(input('輸入矩陣行數n:'))    m=int(input('輸入矩陣列數m:'))    arrayString = input('輸入一個二維數組:')    a=eval(arrayString)    startx = int(input('輸入開始的位置startx:'))    starty = int(input('輸入開始的位置starty:'))    mx = int(input('輸入的終點位置mx:'))    my = int(input('輸入的終點位置my:'))    book=[[0]*51]*51    min=99999999    book[startx][starty]=1    dfs(startx,starty,0)    print("最短步數:%d" % min)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.