题目:将马随机放在国际象棋的8×8棋盘Board[0~7][0~7]的某个方格中,马按走棋规则进行移动。要求每个方格只进入一次,走遍棋盘上全部64个方格
代码实现:
#include <stdio.h> #define N 7 //棋盘大小 typedef struct Pos //马可能走的8个偏移位置 { int ipos; int jpos; }pos; static int chess[N][N]; //定义一个8*8棋盘 static pos offset_pos[8] = { {-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2} }; //定义8个偏移量 //static int count = 1; //定义一个变量,用于存储当前的步数 //初始化棋盘函数 void init() ///传进来的是初始位置的坐标 { int i = 0; int j = 0; for(i = 0; i < N; i++) for(j = 0; j < N; j++) chess[i][j] = 0; //0表示此位置没有被走过 } //显示函数 void display() { int i = 0; int j = 0; for(i = 0; i < N; i++) { for(j = 0; j < N; j++) { printf("%d", chess[i][j]); printf(" "); } printf("\n"); } } //检查下一个位置是否能走 int check(int x, int y, int p) //穿进来的是当前点的坐标 { if( (0 > x + offset_pos[p].ipos) || (0 > y + offset_pos[p].jpos) || (N <= x +offset_pos[p].ipos) || (N <= y + offset_pos[p].jpos) ) return 0; else if( 0 == chess[x + offset_pos[p].ipos][y + offset_pos[p].jpos] ) return 1; else return 0; } //DFS--回溯--递归 int DFS_horse(int x, int y, int count) // 返回之为0;说明寻找不成功 ,count记录第几步 { chess[x][y] = count; //将步数放到棋盘中 if(N*N == count) //边界条件 { display(); return 1; } else { int p = 0; //用于记录偏移量 int m = 0; //用于回溯 int flag = 0; //用于判断是否存在下一步 while(8 > m) { for(p = m; p < 8; p++) { if( check(x, y, p) ) //如果有下一步 { flag = 1; m = p; break; } } if(flag) { if(DFS_horse( (x + offset_pos[m].ipos), (y + offset_pos[m].jpos), count+1 )) return 1; //递归下一步 } else { chess[x][y] = 0; //如果沒有下一步则回溯到上一步之前要将这一步设为可走 return 0; //返回0表明此次寻找不成功,如果回溯到第一步时返回0表明没有可行解 } flag = 0; //回溯的时候要将其置0 , 为了求出所有的结果 m++; } if(8 <= m) { chess[x][y] = 0; return 0; } } } int main() { int ret = 1; init(); //初始化棋盘 ret = DFS_horse(2, 0, 1); printf("%d", ret); }