马的走法

来源:互联网 发布:阿里云备案主体负责人 编辑:程序博客网 时间:2024/06/10 05:33

Problem Description

在一个4×5的棋盘上,求马能返回初始位置的所有不同走法的总数(马走过的位置不能重复,马走“日”字)。

Input

从输入文件中读入数据。文件的第一行马的初始位置的个数n,后面n行是初始位置坐标。

Output

对于每个初始位置给出走法总数,如果不能回到初始位置,输出“ERROR”。

Sample Input

12 2

Sample Output

4596

#include <iostream>
#include <cstring>

using namespace std;

int runs[8][2] = { -2, 1, -1, 2, 1, 2, 2, 1, -2, -1, -1, -2, 1, -2, 2, -1 };
int once[5][6];
int Sx, Sy;
int sum;

void DFS(int x, int y)
{
    int i, newx, newy;
    for (i = 0; i < 8; i++)
    {
        newx = x + runs[i][0];
        newy = y + runs[i][1];
        if(newx >= 1 && newx <= 4&& newy >= 1 && newy <= 5)
        {
            if (newx == Sx && newy == Sy)   sum++;
            else if (once[newx][newy] == 0)
            {
                once[newx][newy] = 1;
                DFS(newx, newy);
                once[newx][newy] = 0;
            }
        }
    }
}

int main ()
{
    int n;
    cin >> n;
    while (n--)
    {
        cin >> Sx >> Sy;
        if (Sx >= 1 && Sx <= 4 && Sy >= 1 && Sy <= 5)
        {
            memset(once, 0, sizeof(once));
            sum = 0; once[Sx][Sy] = 1;  //注意赋值
            DFS(Sx, Sy);
            if (sum)  cout << sum << endl;
            else      cout << "ERROR" << endl;
        }
        else          cout << "ERROR" << endl;
    }
    return 0;
}