G - 马走日

马在中国象棋以日字形规则移动。

请编写一段程序,给定n*m大小的棋盘,以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点。

Input

第一行为整数T(T < 10),表示测试数据组数。
每一组测试数据包含一行,为四个整数,分别为棋盘的大小以及初始位置坐标n,m,x,y。(0<=x<=n-1,0<=y<=m-1, m < 10, n < 10)

Output

每组测试数据包含一行,为一个整数,表示马能遍历棋盘的途径总数,0为无法遍历一次。

Sample Input

1
5 4 0 0

Sample Output

32

深搜题,相当于复习了深搜模板。

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<map>
#include<set>
#include<queue>
#include<stack>
using namespace std;
#define inf 0x3f3f3f3f;
int n,m,stx,sty,ans;
int book[100][100];
int dis[8][2]={{1,2},{2,1},{-1,2},{-2,1},{-1,-2},{-2,-1},{1,-2},{2,-1}};
bool check()
{
    int sum=0;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<m;j++)
        {
            if(book[i][j])
                sum++;
        }

    }
    if(sum==n*m)
        return 1;
    else
        return 0;
}
void cn(int x,int y)
{
    if(check()==1)
    {
        ans++;
        return ;
    }
    else
    {
        for(int i=0;i<8;i++)
        {
            int tx=x+dis[i][0];
            int ty=y+dis[i][1];
            if(tx<0||tx>=n||ty<0||ty>=m||book[tx][ty]==1)
            {
                continue;
            }
            book[tx][ty]=1;
            cn(tx,ty);
            book[tx][ty]=0;
        }
    }
    return ;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(book,0,sizeof(book));
        scanf("%d%d%d%d",&n,&m,&stx,&sty);
        book[stx][sty]=1;
        ans=0;
        cn(stx,sty);
        printf("%d\n",ans);

扫描二维码关注公众号,回复: 4306734 查看本文章

    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/aini875/article/details/84647334