搜索,最短路都可以
#include<stdio.h> #include<string.h> #include<queue> #define inf 0x3fffffff using namespace std; int map[65][65]; int sx,sy,ex,ey; int dis[10][10],link[10][10]; char str[8][3]={"D","R","U","L","RD","LU","LD","RU"}; int dir[8][2]={1,0,0,1,-1,0,0,-1,1,1,-1,-1,1,-1,-1,1}; struct node { int x,y,w; friend bool operator < (node a, node b) { return a.w>b.w; } }cur,next; int judge(int x,int y) { if(x>=1&&x<=8&&y>=1&&y<=8) return 1; return 0; } void bfs() { priority_queue<node> Q; int x,y,i,w,j; for(i=0;i<9;i++) for(j=0;j<9;j++) dis[i][j]=inf; cur.x=sx;cur.y=sy;cur.w=0; dis[sx][sy]=0; Q.push(cur); while(!Q.empty()) { cur=Q.top(); Q.pop(); if(cur.x==ex&&cur.y==ey)return; for(i=0;i<8;i++) { next.x=x=cur.x+dir[i][0]; next.y=y=cur.y+dir[i][1]; if(judge(x,y)==0)continue; next.w=w=cur.w+1; if(w<dis[x][y]) { dis[x][y]=w; Q.push(next); link[x][y]=i; } } } } void prinf(int x,int y) { if(x==sx&&y==sy)return ; int i=link[x][y]; prinf(x-dir[i][0],y-dir[i][1]); printf("%s\n",str[i]); } int main() { char s1[5],s2[5]; while(scanf("%s%s",s1,s2)!=-1) { sy=s1[0]-'a'+1; sx=9-(s1[1]-'0'); ey=s2[0]-'a'+1; ex=9-(s2[1]-'0'); bfs(); printf("%d\n",dis[ex][ey]); prinf(ex,ey); } return 0; }