The shortest path from the beginning of the maze to the end, with depth first search
C Implementation
#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);//The number of steps also takes as the parameter//output shortest steps printf ("%d", min);
return 0; }
Python implements
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 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 return if __name__== ' __main__ ': n=int (Input (' Enter matrix rows N: ') m=int (input
(' Input matrix number m: ') arraystring = input (' Enter a two-dimensional array: ') A=eval (arraystring) startx = Int (input (' Enter start position startx: ') starty = Int ( ' Input start position starty: ') mx = int (input (' endpoint mx: ')) my = Int (input (' endpoint position of input: ') book=[[0]*51]*51 min=999999 Book[startx][starty]=1 dfs (startx,starty,0) print (shortest steps:%d% min)