1219:马走日

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

 1 #include<cstdio>
 2 #include<cstring>
 3 using namespace std;
 4 int t;//表示输入t组数据 
 5 int n, m;//棋盘大小n行,m列 
 6 int stx, sty;//马的初始位置
 7 int book[20][20]={0};//用于标记坐标点是否被遍历过,0表示未遍历,1表示遍历 
 8 int cnt=0;//遍历棋盘的途径总数
 9 //next数组用于存放马走的坐标累加数 
10 int next[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};//8连通坐标变化位移 
11 bool f;//刚开始假定不能遍历 
12 void dfs(int x, int y, int step)
13 {
14     if(step==n*m)//搜索终止条件为每个点都访问过 
15     {
16         cnt++;
17         f=true; 
18         return;
19     }
20     for(int i=0; i<8; i++)
21     {
22         int nx=x+next[i][0];
23         int ny=y+next[i][1];
24         if(nx<0 || nx>=n || ny<0 || ny>=m)continue;//约束条件 
25         if(!book[nx][ny])//约束条件 
26         {
27             book[nx][ny]=1;
28             dfs(nx,ny,step+1);
29             book[nx][ny]=0;
30         }
31     }
32 }
33 int main()
34 {
35     scanf("%d",&t);
36     while(t--)
37     {
38         f=false;//f用于标记是否可以访问完所有点,初始值为false 
39         cnt=0;//用于计数,初始值为0 
40         memset(book,0,sizeof(book));//每次记得重新让book数组清0 
41         
42         scanf("%d%d",&n,&m);
43         scanf("%d%d",&stx,&sty);
44         
45         book[stx][sty]=1;//初始位置标记防止重复访问 
46         dfs(stx,sty,1);
47         if(f)printf("%d\n",cnt);
48         else printf("0\n");
49                 
50     }
51     return 0;
52 }

 

posted @ 2020-10-04 16:08  TFLSNOI  阅读(1033)  评论(0编辑  收藏  举报