遞歸+DFS--簡單迷宮問題--百練2802
阿新 • • 發佈:2018-02-26
sizeof pair printf c代碼 freopen game 一個 mem getch
題目描述
遞歸函數中為什麽最後有一個 =false?
ac代碼:
#include<iostream> #include<cstring> #define maxn 75+2 #define min MIN //min與預定義函數重名... int to[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; bool mark[maxn][maxn]; //標記格子是否走過 char map[maxn][maxn]; int x1,x2,y1,y2; //x1,y1起點 x2,y2終點 int w,h,min; void search(int x1,int y1,int x2,int y2,int step,int f){ //遞歸遍歷 if(step>min) return; if(x1 == x2 && y1 == y2){ //已經到了終點 if(min > step) //更新min 或 返回上一層遞歸 min = step; return; } for(int i=0; i<4 ; i++){ //向四個方向遍歷 int x = x1+to[i][0]; //下一步走x,y int y = y1+to[i][1]; // x,y在邊界內 且( x,y處無卡牌 而且未走過 或 x,y已經到達終點,終點有卡牌 ) if( (x>-1) && (x<w+2) && (y>-1) && (y<h+2) && (((map[y][x]==‘ ‘) && (mark[y][x]==false)) || ((x==x2) && (y==y2) && (map[y][x] == ‘X‘))) ){ //x,y是否合法 mark[y][x] = true; //x,y合法,給一個走過的標記 if(f == i) search(x,y,x2,y2,step,i); //未轉向 step不變 else search(x,y,x2,y2,step+1,i); //轉向 step+1 mark[y][x] = false; //看不懂 } } } int main(){ freopen("in.txt","r",stdin); int i,j,count=0,game=0; while( scanf("%d %d",&w,&h)==2 && w!=0 ){ count=0; game++; printf("Board #%d:\n",game); for(i=1;i<=h;i++){ getchar(); for(j=1;j<=w;j++){ map[i][j]=getchar(); map[0][j]=‘ ‘; map[h+1][j]=‘ ‘; } map[i][0]=‘ ‘; map[i][w+1]=‘ ‘; } map[0][0]=‘ ‘;map[0][w+1]=‘ ‘;map[h+1][0]=‘ ‘;map[h+1][w+1]=‘ ‘; // memset(mark,false,sizeof(mark)); //要不要都行 while(scanf("%d %d %d %d",&x1,&y1,&x2,&y2) && x1>0){ count++; min=100000; search(x1,y1,x2,y2,0,-1); if( min<10000 ) printf("Pair %d: %d segments.\n",count,min); else printf("Pair %d: impossible.\n",count); } printf("\n"); } return 0; }
遞歸+DFS--簡單迷宮問題--百練2802