SDUT 1400 马的走法(回溯法)

题目链接: 传送门

马的走法

Time Limit: 1000MS     Memory Limit: 65536K

题目描述

在一个4*5的棋盘上,马的初始位置坐标(纵 横)位置由键盘输入,求马能返回初始位置的所有不同走法的总数(马走过的位置不能重复,马走“日”字)。如果马的初始位置坐标超过棋盘的边界,则输出ERROR。例如初始位置为4 6,则输出ERROR。

输入

输入数据只有一行,有两个用空格分开的整数,表示马所在的初始位置坐标。首行首列位置编号为(1 1)。

输出

输出一行,只有一个整数,表示马能返回初始位置的所有不同走法的总数。如果输入的马的初始位置超出棋盘边界,则输出ERROR。

输入示例

2 2

输出示例

4596

思路

题目规模小,采用递归回溯方法

#include<iostream>
#include<cstring> 
using namespace std;
const int ROWS = 5;  //行数 
const int COLUMS = 6; //列数 
int chess[ROWS][COLUMS]; //棋盘
int numCount = 0;
int posX,posY;
int direction[2][8]={{-1,-1,-2,-2,2,2,1,1},{-2,2,1,-1,1,-1,2,-2}};

void Solve(int x,int y)
{
	int i,desX,desY;
	for (i = 0;i < 8;i++)
	{
		desX = x + direction[0][i];  //目标位置x坐标
		desY = y + direction[1][i] ;
		if(desX > 0 && desX < 5 && desY > 0 && desY < 6 && chess[desX][desY] == 0)
		{
			//满足规则,走到目标处,并继续搜索
			chess[desX][desY] = 1;
			Solve(desX,desY);
			chess[desX][desY] = 0;   //回溯 
		}
		else
		{
			if(desX == posX && desY == posY)
			{
				//回到了起点
				numCount++; 
			}
	    }
	}
}

int main()
{
	cin >> posX >> posY;
	
	if(posX > 4 || posX < 0 || posY > 5 || posY < 0)
	{
		cout << "ERROR" << endl;
	}
    else
    {
    	memset(chess,0,sizeof(chess));
    	numCount = 0;
    	chess[posX][posY] = 1;
    	Solve(posX,posY);
    	cout << numCount << endl;
    }
	return 0;
} 
原文地址:https://www.cnblogs.com/ZhaoxiCheung/p/5285517.html