//尚未解决
前些日子老师讲到了递归算法,顺带提出了广搜和深搜。以输出组合数为例子介绍了基本思想,留下了几个习题,包括八皇后和马走日等题目。
题目
马在中国象棋以日字形规则移动。
请编写一段程序,给定 n×m大小的棋盘,以及马的初始位置 (x,y),要求不能重复经过棋盘上的同一个点,计算马可以有多少途径遍历棋盘上的所有点。
输入格式
第一行为整数 表示测试数据组数。每一组测试数据包含一行,为四个整数,分别为棋盘的大小以及初始位置坐标
输出格式
每组测试数据包含一行,为一个整数,表示马能遍历棋盘的途径总数,0为无法遍历一次。
Sample Input
1
5 4 0 0
Sample Output
32
于是自己写了一个算法,倒腾了一下,对于题目给出的测试用例能够通过。然而出现了时间超限的问题。
#include<iostream>
#include<stdio.h>
#include<cmath>
#include<cstring>
using namespace std;
int a[8][2] = { 1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-2,1,-1,2 };//把移动方向存入数组
bool b[16][16] = { false };//棋盘。false表示不能再走了
int total = 1,sum=0;//计算总共走的步数
void masearch(int s, int t,int S) {
if (total == S) {sum++; }
else {
for (int i = 0; i < 8; i++){
if (b[s + a[i][0]][t + a[i][1]] == true)
{
s += a[i][0];
t += a[i][1];
total++;
b[s][t] = false;//标记
masearch(s, t, S);
b[s][t] = true;//去除标记
s -= a[i][0];
t -= a[i][1];
total--;
}
}
}
}
int main() {
int m, n,x,y;
cin >> m >> n>>x>>y;
x += 2; y += 2;//避开越界
int S = m * n;
for(int i=2;i<m+2;i++)
{
for (int j = 2; j<n+2;j++)
{
b[i][j] = true;
}
}//初始化棋盘
b[x][y] = false;//起始点
masearch(x, y, S);
cout << sum << endl;
}
思考:如何解决呢?初步分析以后认为,标记和去除标记的过程太繁琐。“退回来”这个过程是不必操作的。
修改以后得到了以下的代码:
#include<iostream>
#include<stdio.h>
#include<cmath>
#include<cstring>
using namespace std;
int a[8][2] = { 1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-2,1,-1,2 };
bool b[15][15] = { false };//false表示不能再走了
int sum=0;
void masearch(int s, int t,int m,int n,int q) {
if (q == m*n) {sum++; }
else {
for (int i = 0; i < 8; i++){
if (b[s + a[i][0]][t + a[i][1]] == true)
{
b[s + a[i][0]][t + a[i][1]] = false;
masearch(s + a[i][0], t + a[i][1], m,n,q+1);
b[s + a[i][0]][t + a[i][1]] = true;
}
}
}
}
int main() {
int m, n,x,y;
cin >> m >> n>>x>>y;
x += 2; y += 2;//避开越界
for(int i=2;i<m+2;i++)
{
for (int j = 2; j<n+2;j++)
{
b[i][j] = true;
}
}//初始化棋盘
b[x][y] = false;//起始点
masearch(x, y, m,n,1);
cout << sum << endl;
}
仍然时间超限。
再次阅读题目要求,自己没有输入测试组数,闹了笑话,以为是自己的算法无法精简。
外面再套一个多组测试数据的格式。注意格式中,一定要重新初始化棋盘(避免小棋盘在大棋盘的true里面计算。),并且把sum清零。
#include<iostream>
using namespace std;
int a[8][2] = { 1,2,2,1,2,-1,1,-2,-1,-2,-2,-1,-2,1,-1,2 };
bool b[15][15] = { false };//false表示不能再走了
int sum = 0;
void masearch(int s, int t, int m, int n, int q) {
if (q == m * n) { sum++; return; }
else {
for (int i = 0; i < 8; i++) {
if (b[s + a[i][0]][t + a[i][1]] == true)
{
b[s += a[i][0]][t += a[i][1]] = false;
masearch(s, t, m, n, q + 1);
b[s][t] = true;
s -= a[i][0];
t -= a[i][1];
}
}
}
}
int main() {
int p;
cin >> p;
for (int s = 1; s <= p; s++) {
int m, n, x, y;
cin >> m >> n >> x >> y;
x += 2; y += 2;//避开越界
for (int i = 2; i <= 14; i++)
{
for (int j = 2; j <= 14; j++) {
if (i < m + 2 && j < n + 2) { b[i][j] = true; }
else { b[i][j] = false; }
}
}
//初始化棋盘,注意不能图方便,避免第二次棋盘更小报错。
b[x][y] = false;//起始点
masearch(x, y, m, n, 1);
cout << sum << endl;
sum = 0;//重要
}
}
终于通过。
总结:第一个是一定注意好深搜的框架,if,添加标记、递归、删除标记。第二个是仔细阅读题目要求,递归的题目中这种时间超限容易和算法问题搅在一起,毕竟递归的时间复杂度的确很高。