從迷宮的起點到終點的最短路徑,用深度優先搜尋
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)