馬踏棋盤(回溯演算法)
阿新 • • 發佈:2019-01-30
馬可以走的位置如圖:
要求: 找到所有馬從任意一個位置出發遍歷整個棋盤的一條路徑
演算法實現:
#include<stdlib.h>
#include<stdio.h>
int chessboard[12][12];//定義棋盤,
//馬走的方向
int move[8][2] = { { 2, 1 }, { 1, 2 }, { -1, 2 }, { -2, 1 }, { -2, -1 }, { -1, -2 }, { 1, -2 }, { 2, -1 } };
int cnt = 1;
int count = 0;
//初始化棋盤
void makeChessBoard(){
for (int i = 0; i < 12; i++){
for (int j = 0; j < 12; j++){
chessboard[i][j] = -1;
}
}
for (int i = 2; i < 10; i++){
for (int j = 2; j < 10; j++){
chessboard[i][j] = 0;
}
}
}
//列印步數
void printGo(){
printf("[馬踏棋盤]第%d組\n", ++count);
for (int i = 2; i < 10; i++){
for (int j = 2; j < 10; j++){
printf("%2d ", chessboard[i][j]);
}
printf("\n\n");
}
}
void horseGoCore(int x, int y){
for (int i = 0; i < 8; i++){
int a = x + move[i][0];
int b = y + move[i][1];
if (!chessboard[a][b]){
chessboard[a][b] = ++cnt;
if (cnt == 64){
printGo();
}
else{
horseGoCore(a, b);
}
chessboard[a][b] = 0;
cnt--;
}
}
}
void horseGo(){
for (int i = 2; i < 10; i++){
for (int j = 2; j < 10; j++){
chessboard[i][j] = 1;
horseGoCore(i, j);
}
}
}
int main(void){
makeChessBoard();
horseGo();
system("pause");
return 0;
}
除錯結果:(相傳解有50多萬組,這裡只展示一組)