马走日—DFS—方案数(回溯)

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

输入格式

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

输出格式

每组测试数据包含一行,为一个整数,表示马能遍历棋盘的途径总数,若无法遍历棋盘上的所有点则输出 0。

数据范围

1≤T≤9,1≤m,n≤9,
1≤n×m≤28,
0≤x≤n−1,
0≤y≤m−1

输入样例:

1
5 4 0 0

输出样例:

32

 不传参步数;

#include <bits/stdc++.h>
#define endl '\n'
#define Bug cout<<"---------------------"<<endl
using namespace std;
constexpr int N = 15;
int dir[8][2] = { {2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1} };//表示八个方向
bool vis[N][N];
int n, m;
int tx, ty;
int ans;
int cnt;
void dfs(int x,int y){
	vis[x][y] = true;
	if (cnt==n*m) {
		ans++;
		ret
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
马走日问题是一种搜索与回溯算法的经典问题,其目的是在一个n×n的棋盘上,让马按照“日”字型的方式遍历每一个格子,即每个格子只能经过一次。下面给出C++的实现代码: ```cpp #include <iostream> #include <cstring> using namespace std; const int MAXN = 10; bool vis[MAXN][MAXN]; int dx[8] = {1, 2, 2, 1, -1, -2, -2, -1}; int dy[8] = {2, 1, -1, -2, -2, -1, 1, 2}; bool check(int x, int y, int n) { if(x < 1 || x > n || y < 1 || y > n) return false; if(vis[x][y]) return false; return true; } void dfs(int x, int y, int step, int n) { if(step == n * n) { cout << "Find the solution:" << endl; for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { cout << vis[i][j] << " "; } cout << endl; } return; } for(int i = 0; i < 8; i++) { int nx = x + dx[i], ny = y + dy[i]; if(check(nx, ny, n)) { vis[nx][ny] = true; dfs(nx, ny, step + 1, n); vis[nx][ny] = false; } } } int main() { memset(vis, false, sizeof(vis)); int n, x, y; cout << "Please input the size of the chessboard and the start position:" << endl; cin >> n >> x >> y; vis[x][y] = true; dfs(x, y, 1, n); return 0; } ``` 在上述代码中,我们使用一个bool类型的二维组vis来记录每个格子是否被访问过。在dfs中,我们首先判断当前格子是否能够被访问,如果能够被访问,则将其标记为已访问,并继续dfs其周围的格子。如果当前遍历的步等于n×n,则表示我们已经找到了一种可行的遍历方案,输出vis组即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ou_fan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值