c++ Knight Moves 超级升级版

Knight Moves 超级升级版

题目描述

棋盘和上次的Knight Moves一样,不过这次的是双人版,有两位玩家

棋子除了可以走日字以外,还能走田字

样例输入

12 16
18 10

样例输出

8
9
Press any to continue...

AC代码

#include <iostream>//includes
#include <string.h>//up
#include <stdio.h>//up
#include <cstdlib>//up
#include <cstring>//up
using namespace std;//
void pause();//写函数让程序暂停
int dx[14] = {0,-2,-2,-1,1,2,2,2,2,1,-1,-2,-2};//dx[] + dy[] 就是棋子走的12个方向 (走日字8个方向 走田字4个方向)
int dy[14] = {0,-1,-2,-2,-2,-2,-1,1,2,2,2,2,1};//up
int main()//main
{
    int s[101][101],que[10000][4] = {0},x1,y1,x2,y2;//定义变量
    memset(s,-1,sizeof(s));//初始化s[]为 -1
    int head = 1,tail = 1;//head出队 tail入队
    que[1][1] = 1;//第一个x坐标为1
    que[1][2] = 1;//第一个y坐标为1
    que[1][3] = 0;//没有父节点所以到上一个节点的距离是0 第一个数的初始距离
    cin >> x1 >> y1 >> x2 >> y2;//x1和y1 是玩家1的xy坐标 x2y2是玩家2的xy坐标
    while (head <= tail)//防止越界
    {
        for (int d = 1;d <= 12;d ++)//循环枚举12个方向
        {
            int x = que[head][1] + dx[d];
            int y = que[head][2] + dy[d];
            if (x > 0 && y > 0)//判断枚举到的位置是否在棋盘上 (没有穿墙)
            {
                if (s[x][y] == -1)//如果这个位置没有判断过 (初始值就是-1)
                {
                    s[x][y] = que[head][3] + 1;//计算这个位置到(1,1)的最短距离
                    tail ++;//开始入队
                    //把xys都保留在此位置的s[][]数组上面
                    que[tail][1] = x//;que[][1] 存储所有x坐标
                    que[tail][2] = y;//que[][2] 存储所有y坐标
                    que[tail][3] = s[x][y];//que[][3]存储所有距离
                    if (s[x][y] > 0 && s[x2][y2] > 0 && s[x1][y1] > 0)//(x1,y1)(x2,y2)都被选择,就输出,再退出
                    {
                        cout << s[x1][y1] << endl;//打印玩家1的步数
                        cout << s[x2][y2] << endl;//打印玩家2的步数
                        pause();//让程序暂停
                        return 0;//直接退出
                    }
                }
            }
        }
        head ++;//如果能够顺利执行到这里的话,说明这个数已经被去除 那么就出队
    }
}
void pause()//写函数让程序暂停
{
    cout << "Press any to continue..." << endl;
    getchar();
}

原文地址:https://www.cnblogs.com/LJA001162/p/11271257.html