回溯法求迷宫问题

    技术2022-05-20  62

    csdn如何修改自己的文章?

    为什么我每次修改都不成功,索性将原来的文章给删除了!

     

    /*@created by Hzj 2011-4-8 14:43:35 */ #include <stdio.h> #include <stdlib.h> int count=0;/*记录总的走法*/ void find_path(char **,char **,int m,int n,int i,int j,int ex); void main() { int m,n,i,j; int en,ex; printf("Input the rows and the cols of the maze!/n"); scanf("%d%d",&m,&n); printf("Input the enter row and the exit row of the maze!/n"); scanf("%d%d",&en,&ex); char **a=(char **)malloc(sizeof(char *)*m); char **path=(char**)malloc(sizeof(char*)*m); for(i=0;i<n;i++) { a[i]=(char *)malloc(sizeof(char)*n); path[i]=(char *)malloc(sizeof(char)*n); } for(i=0;i<m;i++) for(j=0;j<n;j++) { path[i][j]=0; } path[en][0]=1; FILE *fp=fopen("maze.txt","r"); if(NULL==fp) { printf("maze.txt is not exist!/n"); return; } FILE *f=fp; for(i=0;i<m;i++) for(j=0;j<n;j++) { char c; while(1) { if((c=fgetc(f))!='/n' && c!='/0') { a[i][j]=c; break; } } } for(i=0;i<m;i++) { for(int j=0;j<n;j++) { a[i][j]-=48; printf("%d ",a[i][j]); } printf("/n"); } printf("/n"); find_path(a,path,m,n,en,0,ex); printf("%d/n",count); } void find_path(char **a,char **path,int m,int n,int i,int j,int ex) { if(i==ex && j==n-1) { count++; /*本来想打印出来各种路径可是总数太多故只打印总的次数 总共的走法居然有80640总 T_T汗*/ /* for(int i=0;i<m;i++) { for(int j=0;j<n;j++) { printf("%d ",path[i][j]); } printf("/n"); } */ return ; } if(i-1>=0 && a[i-1][j] == 0 && path[i-1][j]==0) { path[i-1][j]=1; find_path(a,path,m,n,i-1,j,ex); path[i-1][j]=0; } if(i-1>=0 && j+1<n && path[i-1][j+1]==0 && a[i-1][j+1]==0) { path[i-1][j+1]=1; find_path(a,path,m,n,i-1,j+1,ex); path[i-1][j+1]=0; } if(j+1<n && path[i][j+1]==0 && a[i][j+1]==0) { path[i][j+1]=1; find_path(a,path,m,n,i,j+1,ex); path[i][j+1]=0; } if(i+1<m && j+1<n && path[i+1][j+1]==0 && a[i+1][j+1]==0) { path[i+1][j+1]=1; find_path(a,path,m,n,i+1,j+1,ex); path[i+1][j+1]=0; } if(i+1<m && path[i+1][j]==0 && a[i+1][j]==0) { path[i+1][j]=1; find_path(a,path,m,n,i+1,j,ex); path[i+1][j]=0; } if(i+1<m && j-1>=0 && path[i+1][j-1]==0 && a[i+1][j-1]==0) { path[i+1][j-1]=1; find_path(a,path,m,n,i+1,j-1,ex); path[i+1][j-1]=0; } if(j-1>=0 && path[i][j-1]==0 && a[i][j-1]==0) { path[i][j-1]=1; find_path(a,path,m,n,i,j-1,ex); path[i][j-1]=0; } if(i-1>=0 && j-1>=0 && path[i-1][j-1]==0 && a[i-1][j-1]==0) { path[i-1][j-1]=1; find_path(a,path,m,n,i-1,j-1,ex); path[i-1][j-1]=0; } return; } 

    贴上迷宫图

    1表示围墙0表示通路

    11111111111111111

    00100011000111111

    11000110111001111

    10110000111100111

    11101111011011001

    11101001011111111

    10011011101001011

    10011011101001011

    10111100111111111

    10011011011111011

    11100011011000001

    10011111000111101

    10100111110111100

    11111111111111111


    最新回复(0)