现在的位置: 首页 > 综合 > 正文

简单搜索题:马的走法

2013年12月10日 ⁄ 综合 ⁄ 共 937字 ⁄ 字号 评论关闭

      一个4×5的棋盘,输入马的起始坐标,求马能返回初始位置的所有不同走法的总数(马走过的位置不能重复,马走字)。

#include <iostream>
using namespace std;

const int ROWS = 4;//行数
const int COLUMS = 5;//列数
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,j,desX,desY;
    
for (i=0;i<8;++i)
    {
        desX 
= x+direction[0][i];//目标位置x坐标
        desY = y+direction[1][i];//目标位置y坐标
        if (desX>=0&&desX<4&&desY>=0&&desY<5&&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;
    memset(chess,
0,sizeof(chess));
    numCount 
= 0;//走法数
    chess[posX][posY] = 1;//起始步
     Solve(posX,posY);//开始搜索
    cout<<numCount<<endl;
    system(
"pause");
    
return 0;
}

抱歉!评论已关闭.