1219 马走日

http://ybt.ssoier.cn:8088/problem_show.php?pid=1219

#include<bits/stdc++.h>
using namespace std;
int t;//测试组数 
int n, m;//地图行列 
int stx, sty;//初始位置 
int book[20][20]={0};//判定是否走过 
int cnt=0;//计数 
int next[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};//八个方向 
bool f;//特判 
void dfs(int x, int y, int step)
{
    if(step==n*m)//一步一点,当走的步数与点数相等,即一种方法已经走完,计数+1,并回溯 
    {
        cnt++;
        f=true;
        return;
    }
    for(int i=0; i<8; i++)//八个方向遍历 
    {
        int nx=x+next[i][0];//下个点的横坐标 
        int ny=y+next[i][1];//下个点的纵坐标 
        if(nx<0 || nx>=n || ny<0 || ny>=m)continue;//边境 
        if(!book[nx][ny])//边境:可以走 
        {
            book[nx][ny]=1;
            dfs(nx,ny,step+1);
            book[nx][ny]=0;//遍历后恢复 
        }
    }
}
int main()
{
    cin>>t;
    while(t--)
    {
        f=false;//初始假定不能 
        cnt=0;
        memset(book,0,sizeof(book));
        cin>>n>>m>>stx>>sty;
        book[stx][sty]=1;//脚下标记为已走过 
        dfs(stx,sty,1);
        if(f) cout<<cnt<<endl;
        else cout<<"0"<<endl;

    }
    return 0;
}
原文地址:https://www.cnblogs.com/qwn34/p/13768364.html