OpenJ_Bailian - 4123 马走日(DFS)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/UncleJokerly/article/details/84244628

马在中国象棋以日字形规则移动。

请编写一段程序,给定n*m大小的棋盘,以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点。

Input

第一行为整数T(T < 10),表示测试数据组数。 
每一组测试数据包含一行,为四个整数,分别为棋盘的大小以及初始位置坐标n,m,x,y。(0<=x<=n-1,0<=y<=m-1, m < 10, n < 10)

Output

每组测试数据包含一行,为一个整数,表示马能遍历棋盘的途径总数,0为无法遍历一次。

Sample Input

1
5 4 0 0

Sample Output

32

解题思路:DFS

这道题最重要的应该是明白这道题中的“马”是如何走下一步的= =

找好八个方向以后即可使用DFS对整个图进行遍历判断

AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
using namespace std;

int n,m,sum,book[15][15];
int nx[8][2]={-2,1,-1,2,1,2,2,1,2,-1,1,-2,-1,-2,-2,-1};

void dfs(int x,int y,int step)
{
	if(step==n*m)
	{
		//printf("************\n");
		sum++;
		return;
	}
	for(int i=0;i<8;i++)
	{
		//printf("#############\n");
		int tx=x+nx[i][0];
		int ty=y+nx[i][1];
		if(tx>=0&&tx<n&&ty>=0&&ty<m&&book[tx][ty]==0)
		{
			book[tx][ty]=1;
			dfs(tx,ty,step+1);
			book[tx][ty]=0;
		}
	}
}

int main()
{
	int t,sx,sy;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d%d%d",&n,&m,&sx,&sy);
		sum=0;
		memset(book,0,sizeof(book));
		book[sx][sy]=1;
		dfs(sx,sy,1);
		printf("%d\n",sum);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/UncleJokerly/article/details/84244628