題目:
假設國際象棋棋盤有5*5共25個格子。設計一個程序,使棋子從初始位置開始跳馬,需要將棋盤的格子全部都走一遍,每個格子只允許走一次。
問:總共有多少解。
思路:
DFS:
將起點作爲搜索的起點,然後枚舉馬的八個走向,由於不是每個馬都有八個走向,所以每走一步就要判斷有沒有越界,如果沒有,就將當前點做爲新的起點,然後繼續遞歸走下一步,並把走過的地方標記爲true,直到走到無路可走就結束遞歸,並且步數等於24時意味着遍歷了所有格子(以(0,0)爲起點),方案數加1。
ps: 總共有25個格子,sign[0][0] == true,只剩下24個格子,所以等 steps == 24 時相當於遍歷結束。
#include<iostream>
#include<algorithm>
bool sign[5][5];
static int method = 0;
int dx[] = {-2,-2,-1,-1,1,1,2,2};
int dy[] = {1,-1,2,-2,2,-2,1,-1};
bool check_boundary(int x, int y)
{
if(sign[x][y] == true) //note1
return false;
if(x>=5 || x<0 || y<0 || y>=5)
return false;
return true;
}
void dfs(int steps, int x, int y)
{
if(steps == 24)
{
method++;
return;
}
// Judge boundary
for(int i = 0; i <= 7; i++)
{
int m = x + dx[i];
int n = y + dy[i];
if( check_boundary(m ,n) )
{
sign[m][n] = true; //mark: this grid has been covered
dfs(steps+1, m, n);
sign[m][n] = false;
}
}
}
int main()
{
sign[0][0] = true;
dfs(0,0,0);
std::cout <<"total methods:" << method << std::endl;
}
result:total methods --> 304
- 分享一個coding時遇到的小bug,希望大家不要像我一樣粗心!源碼中 note1的位置應該是
sign[x][y] == true;
而不是sign[x][y] = true;
噢!
以下是這個bug的結果: