第一题
#include<iostream> using namespace std; /* 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0 */ int book[5][5]={0}; int map[5][5]; int next[4][2]={{0,1},{1,0},{0,-1},{-1,0}}; int tx,ty; /* void dfs(int x,int y,int step) { if(x==4&&y==4) { if(min1>step) { min1=step; } return; } for(int i=0;i<4;i++) { tx=x+next[i][0]; ty=y+next[i][1]; if(tx<0||ty<<0||tx>4||ty>4) { continue; } if(book[tx][ty]==0&&map[tx][ty]==0) { book[tx][ty]=1; dfs(tx,ty,step+1); book[tx][ty]=0; } } return ; } */ void print(int x,int y) { cout<<"("<<x<<","<<y<<")"<<endl; } typedef struct node { int x; int y; int step; int prestep; }node; node que[1000]; void printPath(int num ) { if(num!=0) { printPath(que[num].prestep); } cout<<"("<<que[num].x<<","<<que[num].y<<")"<<endl; } void bfs(int x,int y,int step) { for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { cin>>map[i][j]; } } cout<<"***"<<endl; for(int i=0;i<5;i++) { for(int j=0;j<5;j++) { cout<<map[i][j]<<" "; } cout<<endl; } int head,tail; head=tail=0; que[tail].x=0; que[tail].y=0; que[tail].prestep=-1; que[tail].step=0; tail++; book[0][0]=1; int flag=0; while(head<tail) { for(int i=0;i<4;i++) { tx=que[head].x+next[i][0]; ty=que[head].y+next[i][1]; if(tx<0||ty<0||tx>4||ty>4) { continue; } if(book[tx][ty]==0&&map[tx][ty]==0) { que[tail].step=que[head].step+1; que[tail].x=tx; que[tail].y=ty; que[tail].prestep=head; book[tx][ty]=1; tail++; } if(tx==4&&ty==4) { flag=1; break; } } if(flag==1) { break; } head++; } int res=tail-1; printPath(res); } int main() { bfs(0,0,0); return 0; }
运行结果: