①用递归做,会超时
#include <iostream> #include <string> #include <stack> #include <queue> using namespace std; int maze[1005][1005]; int mark[1005][1005]; int xb,yb,xe,ye; struct position { int px,py; }point[9999]; struct Offsets { int dx,dy; Offsets(int x=0,int y=0):dx(x),dy(y) {} }; Offsets guide[4]= { {1,0},{0,-1},{-1,0},{0,1} }; int f=0; void dfs(int xb,int yb,int step) { if(xb==xe && yb==ye) { for(int i=0;i<step;i++) cout<<point[i].py<<" "<<point[i].px<<endl; // cout<<endl; f=1; return; } for(int i=0;i<4;i++) { int x = xb+guide[i].dx; int y = yb+guide[i].dy; if(mark[x][y] == 0 || mark[x][y]==4) { mark[x][y] = 1; point[step].px = x; point[step].py = y; dfs(x,y,step+1); if(f==1) return; mark[x][y] = 0; } } if(f==1) return; } int main() { int N,M; cin>>N>>M; //初始化 for(int i=0; i<M; i++) for(int j=0; j<N; j++) { cin>>maze[i][j]; mark[i][j] = maze[i][j]; if(maze[i][j] == 3) { xb = i; yb = j; } if(maze[i][j] == 4) { xe = i; ye = j; } } /* for(int i=0; i<M; i++) { for(int j=0; j<N; j++) cout<<maze[i][j]; cout<<endl; }*/ point[0].px = xb; point[0].py = yb; dfs(xb,yb,1); return 0; } /* 8 10 1 1 1 1 1 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 0 1 0 1 1 1 0 3 1 0 1 1 1 0 0 1 0 0 4 1 1 0 0 0 0 1 1 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 */
②用栈的思想做
#include <iostream> #include <string> #include <stack> #include <queue> using namespace std; /* 8 10 1 1 1 1 1 1 1 1 1 0 1 1 0 1 0 1 1 0 1 0 0 1 0 1 1 1 0 3 1 0 1 1 1 0 0 1 0 0 4 1 1 0 0 0 0 1 1 1 1 0 1 0 0 1 0 1 1 0 1 0 0 0 1 1 1 1 1 1 0 0 0 1 1 1 1 1 1 1 1 1 */ int maze[1005][1005]; int mark[1005][1005]; int xb,yb,xe,ye; struct position { int px,py; } point[99999]; struct Offsets { int dx,dy; Offsets(int x=0,int y=0):dx(x),dy(y) {} }; Offsets guide[4]= { {1,0},{0,-1},{-1,0},{0,1} }; int main() { int N,M; cin>>N>>M; //初始化 for(int i=0; i<M; i++) for(int j=0; j<N; j++) { cin>>maze[i][j]; mark[i][j] = maze[i][j]; if(maze[i][j] == 3) { xb = i; yb = j; } if(maze[i][j] == 4) { xe = i; ye = j; } } /* for(int i=0; i<M; i++) { for(int j=0; j<N; j++) cout<<maze[i][j]; cout<<endl; }*/ point[0].px = xb; point[0].py = yb; int t = 0; while(1) { int ff = 0; for(int i=0; i<4; i++) { int x = point[t].px+guide[i].dx; int y = point[t].py+guide[i].dy; if(mark[x][y] == 0 && maze[x][y] == 0) { t++; mark[x][y] = 1; point[t].px = x; point[t].py = y; ff = 1; break; } if(maze[x][y] == 4) { for(int i = 0; i <= t; i++) cout<<point[i].py<<' '<<point[i].px<<endl; cout<<y<<' '<<x<<endl; return 0; } } if(ff==0) t--; } return 0; }