回溯法-马走日

vjudge 马走日

马在中国象棋以日字形规则移动。请编写一段程序,给定n*m大小的棋盘,以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点。
Input
第一行为整数T(T < 10),表示测试数据组数。每一组测试数据包含一行,为四个整数,分别为棋盘的大小以及初始位置坐标n,m,x,y。(0<=x<=n-1,0<=y<=m-1, m < 6, n < 6)
Output
每组测试数据包含一行,为一个整数,表示马能遍历棋盘的途径总数,0为无法遍历一次。
Sample Input
1
5 4 0 0
Sample Output
32

注意事项:
提交代码前把HelloWorld删掉

代码

#include <iostream>

using namespace std;
int a[20][20];
int x,y,m,n;
int step=0;
int times;

int dx[]= {1,2,2,1,-1,-2,-2,-1}; //= {-1,1,2,2,1,-1,-2,-2};
int dy[]= {2,1,-1,-2,-2,-1,1,2}; // {-2,-2,-1,1,2,2,1,-1};
void fun(int x,int y ,int step)
{
    if(step>=m*n)
    {
        times++;
        return;
    }
   // cout<<step<<endl;
    for(int i=0;i<8;i++)
    {
        int nx=x+dx[i],ny=y+dy[i];
        if(nx<m&&nx>-1&&ny<n&&ny>-1&&a[nx][ny]==0)
        {
            a[nx][ny]=1;
            fun(nx,ny,step+1);
            a[nx][ny]=0;
        }
    }
}
void input()
{
    cin>>m>>n>>x>>y;
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
           {
               a[i][j]=0;
           }
    }
    times=0;
    a[x][y]=1;
    step=1;
    fun(x,y,step);
    cout<<times<<endl;

}
int main()
{
    int t;
    cin>>t;
    while(t)
    {
          cin>>m>>n>>x>>y;
    for(int i=0;i<m;i++)
    {
        for(int j=0;j<n;j++)
            a[i][j]=0;
    }
    times=0;
    a[x][y]=1;
    step=1;
    fun(x,y,step);
    cout<<times<<endl;
         t--;
    }

    //cout << "Hello world!" << endl;
    return 0;
}
/**
马在中国象棋以日字形规则移动。请编写一段程序,给定n*m大小的棋盘,
以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马
可以有多少途径遍历棋盘上的所有点。

Input
第一行为整数T(T < 10),表示测试数据组数。每一组测试数据包含一行,
为四个整数,分别为棋盘的大小以及初始位置坐标n,m,x,y。
(0<=x<=n-1,0<=y<=m-1, m < 6, n < 6)
Output
每组测试数据包含一行,为一个整数,表示马能遍历棋盘的途径总数,
0为无法遍历一次。
Sample Input
1
5 4 0 0



2
5 4 4 3
5 4 0 0
Sample Output
32
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值