國際象棋的棋盤為8*8的方格棋盤。現將"馬"放在任意指定的方格中,按照"馬"走棋的規則將"馬"進行移動。要求每個方格只能進入一次,最終使得"馬"走遍棋盤的64個方格。編寫一個C程序,實現馬踏棋盤操作,要求用1~64這64個數字標注馬移動的路徑,也就是按照求出的行走路線,將數字1,2,……64依次填入棋盤的方格中,並輸出。
解決馬踏棋盤問題的一種比較容易理解的方法是應用遞歸的深度優先搜索的思想。
1 /* 2 * ChessHorse.h 3 * 4 * Created on: 2016年2月24日 5 * Author: hoojjack 6 */ 7 8 #pragma once 9 #include <stdio.h> 10 #include <stdlib.h> 11 #include <time.h> 12 #include <windows.h> 13 namespace section10_horseMove{ 14 typedef struct { 15 int x; 16 int y; 17 }Coordinate; 18 int chessBoard[8][8]; 19 int curstep; 20 Coordinate direction[8]={{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1}}; 21 void outPut(int (*chess)[8]){ 22 for(int i=0;i<8;i++){ 23 for(int j=0;j<8;j++){ 24 printf("%d\t",chess[i][j]); 25 } 26 printf("\n"); 27 } 28 } 29 /* 30 * 按照一條路先一直往下走,如果沒有合適的路就按原路返回,同時恢復現場,這樣直到將所有的路徑都試到 31 */ 32 void horseMove(Coordinate temp){ 33 Coordinate next; 34 if(temp.x<0||temp.x>7||temp.y<0||temp.y>7){ 35 return ; 36 } 37 if(chessBoard[temp.x][temp.y]){ 38 return; 39 } 40 chessBoard[temp.x][temp.y]=curstep; 41 curstep++; 42 if(curstep>64){ 43 outPut(chessBoard); 44 exit(0); 45 }else{ 46 for(int i=0;i<8;i++){ 47 next.x=temp.x+direction[i].x; 48 next.y=temp.y+direction[i].y; 49 if(next.x<0||next.x>7||next.y<0||next.y>7){ 50 continue; 51 }else{ 52 horseMove(next); 53 } 54 } 55 } 56 //outPut(chessBoard); 57 //Sleep(100); 58 chessBoard[temp.x][temp.y]=0; 59 //outPut(chessBoard); 60 curstep--; 61 //Sleep(100); 62 // printf("A barrier!\n "); 63 } 64 65 void runHorseMove(){ 66 Coordinate start; 67 printf("Please input the first location of the horse!\n"); 68 scanf("%d%d",&start.x,&start.y); 69 if(start.x<0||start.x>7||start.y<0||start.y>7){ 70 printf("The location is error"); 71 exit(0); 72 } 73 for(int i=0;i<8;i++){ 74 for(int j=0;j<8;j++){ 75 chessBoard[i][j]=0; 76 } 77 } 78 curstep=1; 79 horseMove(start); 80 } 81 82 }