马的走法

来源:互联网 发布:爱奇艺网络电影票房 编辑:程序博客网 时间:2024/06/02 15:01

描述

在一个4X5的棋盘上,马的起始位置坐标(纵、横)位置由键盘输入,求马能返回初始位置的所有不同走法的总数(马走过的位置不能重复,马走“日”字)。

输入

输入文件第一行为测试用例的个数N,接下来N行,每行两个正整数x,y(1<=x<=5,1<=y<=6),表示马的位置坐标.

输出

每个测试用例的输出占一行,输出马能返回初始位置的所有不同走法的总数,如果没有,则输出“ERROR”(不包含双引号)。

样例输入

3
2 2
1 1
4 6

样例输出

4596
1508
ERROR

一道简单的搜索题
解题步骤:(1)读入马的起始位置,进行合法性判断;
                (2)从起始位置开始搜索,搜索方法采用深搜,累计总数;
                (3)输出结果。


#include<iostream>#include<stdio.h>#include<string.h>#include<cmath>using namespace std;int dir[8][2]={{-1,2},{-2,1},{-1,-2},{-2,-1},{1,-2},{2,-1},{1,2},{2,1}};bool mk[10][10];int res,sx,sy;void dfs(int x,int y){    if(mk[x][y])    {        if(x==sx && y==sy) ++res;        return ;    }    mk[x][y]=true;    for(int i=0;i<8;i++)    {        int dx=x+dir[i][0];        int dy=y+dir[i][1];        if(dx>=1 && dx<=4 && dy>=1 && dy<=5) dfs(dx,dy);    }    mk[x][y]=false;}int main(){    int cs;    scanf("%d",&cs);    while(cs--)    {        scanf("%d %d",&sx,&sy);        res=0;        memset(mk,false,sizeof(mk));        dfs(sx,sy);        if(res) cout<<res<<endl;        else        cout<<"ERROR"<<endl;    }    return 0;}


原创粉丝点击