网站:http://ybt.ssoier.cn:8088/index.php
一本通1219马走日,为什么不过?
【题目描述】
马在中国象棋以日字形规则移动。
请编写一段程序,给定n×m大小的棋盘,以及马的初始位置(x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点。
【输入】
第一行为整数T(T < 10),表示测试数据组数。
每一组测试数据包含一行,为四个整数,分别为棋盘的大小以及初始位置坐标n,m,x,y。(0≤x≤n-1,0≤y≤m-1, m < 10, n < 10)。
【输出】
每组测试数据包含一行,为一个整数,表示马能遍历棋盘的途径总数,0为无法遍历一次。
【输入样例】
1
5 4 0 0
【输出样例】
32
代码
#include
using namespace std;
int m,n,x,y,tot;
int a[15][15],
movex[8]={1,1,2,2,-1,-1,-2,-2},
movey[8]={2,-2,1,-1,2,-2,1,-1};
void search(int num)
{
for(int i=0;i<8;i++)
if(a[y+movey[i]][x+movex[i]]==0&&x+movex[i][i]>=0&&y+movey[i][i]>=0){
x+=movex[i];
y+=movey[i];
a[y][x]=1;
if(num==n*m)tot++;//共走过m*n个格子时,遍历棋盘
else search(num+1);
a[y][x]=0;
x-=movex[i];
y-=movey[i];
}
}
int main()
{
int t;
cin>>t;
for(int i=1;i<=t;i++)
{
cin>>n>>m>>x>>y;
a[x][y]=1;
search(2);//算上起始点,从第二个落点开始搜索
cout<
样例什么的都过了,自己有是了几组数据,结果都是对的,但就是不通过。
是因为格式不对还是答案还是别的?
#include <bits/stdc++.h>
using namespace std;
typedef pair<string,string> PII;
typedef long long LL;
const int N = 10;
int n, m,sx,sy;
int ans;//全局变量记录答案
bool st[N][N];
//8个方向
int dx[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
int dy[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
void dfs(int x, int y, int cnt) {
if (cnt == n * m) {
ans++;
return;
}
st[x][y] = true;
for (int i = 0; i < 8; i++) {
int a = x + dx[i], b = y + dy[i];
if (a < 0 || a >= n || b < 0 || b >= m)continue;
if (st[a][b])continue;
dfs(a, b, cnt + 1);
}
st[x][y] = false;
}
int main()
{
int T;
cin >> T;
while (T--) {
int x, y;
cin >> n >> m >> x >> y;
memset(st, false, sizeof st);
ans = 0;
dfs(x, y, 1);
cout << ans << endl;
}
return 0;
}