UVa 439 Knight Moves 骑士的移动

    xiaoxiao2024-12-25  16

    思路:BFS求最短路,遇到终点直接结束

    <span style="font-size:14px;">#include<iostream> #include<queue> #include<cstdio> #include<cstring> using namespace std; int d[8][2] = {{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}}; int begin1,begin2,end1,end2; int chess[8][8]; struct Point{ int x,y; int leng; }; queue<Point> q; int bfs() { int kase = 0; Point begin,tmp; begin.x = begin1; begin.y = begin2; begin.leng = 0; q.push(begin); while(!q.empty()) { Point n; n = q.front(); q.pop(); for(int i = 0;i<8;i++) { tmp.x = n.x+d[i][0]; tmp.y = n.y+d[i][1]; tmp.leng = n.leng + 1; if (tmp.x==end1&&tmp.y==end2) return n.leng+1; else { if(tmp.x>=0&tmp.x<8&tmp.y>=0&&tmp.y<8) { q.push(tmp); } } } } } int main() { char c[5],h[5]; while(scanf("%s %s", c, h) != EOF) { memset(chess,0,sizeof(chess)); while (!q.empty()) q.pop(); begin1 = c[0]-'a'; begin2 = c[1]-'1'; end1 = h[0] - 'a'; end2 = h[1] - '1'; int x; if (begin1==end1&&begin2==end2) x = 0; else x = bfs(); printf("To get from %s to %s takes %d knight moves.\n",c,h,x); } return 0; }</span>

    转载请注明原文地址: https://ju.6miu.com/read-1294982.html
    最新回复(0)