马的遍历

问题描述

在n*m格的棋盘上,有一只中国象棋的马,从(0,0)点出发,按日字跳马,
它可以朝8个方向跳,但不允许出界或跳到已跳过的格子上,求马不重复的跳遍棋盘的方法总数。
请注意,马是在格子的顶点走的。例如中国象棋棋盘如下,是9x8的棋盘。

输入

输入只有两个整数n和m(m*n<=20)

输出

在单独的一行中输出马不重复的跳遍棋盘的方法总数。

输入样列
3 2
输出样例
2
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int dis[8][2]={{1,2},{-1,2},{1,-2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
 4 int n,m,step,t;
 5 int book[30][30];
 6 void dfs(int x,int y,int step)
 7 {
 8     if(step>n*m)
 9     {
10         t++;
11         return;
12     }
13     for(int k=0;k<8;k++)
14     {
15         int nx=dis[k][0]+x;
16         int ny=dis[k][1]+y;
17         if(nx>=0&&nx<n&&ny>=0&&ny<m&&!book[nx][ny])
18         {
19             book[nx][ny]=1;
20             dfs(nx,ny,step+1);
21             book[nx][ny]=0;
22         }
23     }
24 }
25 int main()
26 {
27     cin>>n>>m;
28     book[0][0]=1;
29     dfs(0,0,1);
30     cout<<t<<endl;
31     return 0;
32 }

待查错

posted @ 2021-04-16 22:01  Queens'  阅读(363)  评论(0)    收藏  举报