1. 程式人生 > >在半個中國象棋棋盤上,馬在左下角(1,1)處,馬走日字,求到指定位置有多少種走法

在半個中國象棋棋盤上,馬在左下角(1,1)處,馬走日字,求到指定位置有多少種走法

在半個中國象棋棋盤上,馬在左下角(1,1)處,馬走日字…而且只能往右走…不能向左…可上可下…求從起點到(m, n)處有幾種不同的走法。
分析:
半個中國象棋棋盤可用二維陣列來表示:static int chessboard[5][9];
能走的方向用陣列來表示:
const int dx[4] = {2, 1, -1, -2};
const int dy[4] = {1, 2, 2, 1};

#include<iostream>

using namespace std;

static int chessboard[5][9];
static int count=0
; /* 馬走日的方向,(dx, dy),dx表示5行中的第幾行的豎直方向,dy表示9列中第幾列的橫方向。 上:(2, 1) 上右:(1, 2) 下右:(-1, 2) 下: (-2, 1) */ const int dx[4] = {2, 1, -1, -2}; const int dy[4] = {1, 2, 2, 1}; void horse_count(int srcx, int srcy, int destx, int desty) { if(srcx>=0 && srcx<5 && srcy>=0 && srcy<9
&& chessboard[srcx][srcy]==0) { if(srcx == destx-1 && srcy == desty-1) { count++; return; } //標記為已經走過 chessboard[srcx][srcy] = 1; int i; for(i=0; i<4; ++i) { horse_count(srcx+dx[i], srcy+dy[i], destx, desty); } //當走完四個方向後,回溯到之前走過的一步,標記為未走過。
chessboard[srcx][srcy] = 0; } } int main() { cout<<"請輸入要到達棋盤的座標: "; int m, n; cin>>m>>n; horse_count(0, 0, m, n); cout<<"走法的種數:"<<count<<endl; return 0; }