很简单的bfs,各点都从0开始保存,可以用%和/确定x,y省空间
/* author:jxy lang:C/C++ university:China,Xidian University **If you need to reprint,please indicate the source** */ #include <cstdio> #include <cstring> #include <queue> #define place(x,y) x+y*6 using namespace std; const int dir[4][2]={0,-1,1,0,0,1,-1,0}; const char d[4]={'N','E','S','W'}; bool no[7][7][4]; int vis[40],start,end,now,next; queue<int> q; void output(int x) { if(x==start)return; output(vis[x]/10); printf("%c",d[vis[x]%10]); } int main() { int x,y,tx,ty,i; while(scanf("%d%d",&x,&y)&&x+y) { memset(no,0,sizeof(no)); memset(vis,0,sizeof(vis)); while(!q.empty())q.pop(); start=place(--x,--y); scanf("%d%d",&x,&y); end=place(--x,--y); for(i=0;i<3;i++) { scanf("%d%d%d%d",&x,&y,&tx,&ty); if((x==tx&&(x==0||x==6))||(y==ty&&(y==0||y==6)))continue; if(x==tx) for(;y<ty;y++) no[x][y][3]=no[x-1][y][1]=1; else for(;x<tx;x++) no[x][y][0]=no[x][y-1][2]=1; } vis[start]=-1; q.push(start); while(!q.empty()&&!vis[end]) { now=q.front();q.pop(); x=now%6;y=now/6; for(i=0;i<4;i++) { tx=x+dir[i][0]; ty=y+dir[i][1]; next=place(tx,ty); if(tx<0||tx>5||ty<0||ty>5||no[x][y][i]||vis[next])continue; vis[next]=now*10+i; q.push(next); } } output(end); puts(""); } }