Maze Shortest Path Depth First search-c-python__python

Source: Internet
Author: User

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) 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.