马踏棋盘问题

来源:互联网 发布:windows的任务栏 编辑:程序博客网 时间:2024/04/30 20:33

问题描述:将马随机放在国际象棋的Board[0~7][0~7]的某个方格中,马按走棋规则进行移动。走遍棋盘上全部64个方格并且不能重复。求出马的行走路线,并按求出的行走路线,将数字1,2,…,64依次填入一个8×8的方阵,输出之,

使用的思想可以理解为图的深度优先遍历。

#include<stdio.h>#include<time.h>#define CHESS_SIZE 5int chess[CHESS_SIZE][CHESS_SIZE];int getNextPosition(int* x, int* y, int counter){switch(counter){case 1:if( *x - 2 >= 0 && *y - 1 >= 0 && chess[*x-2][*y-1] == 0 ){*x -= 2;*y -= 1;return 1;}break;case 2:if( *x - 2 >= 0 && *y + 1 < CHESS_SIZE && chess[*x-2][*y+1] == 0 ){*x -= 2;*y += 1;return 1;}break;case 3:if( *x - 1 >= 0 && *y + 2 < CHESS_SIZE && chess[*x-1][*y+2] == 0 ){*x -= 1;*y += 2;return 1;}break;case 4:if( *x + 1 < CHESS_SIZE && *y + 2 < CHESS_SIZE && chess[*x+1][*y+2] == 0 ){*x += 1;*y += 2;return 1;}break;case 5:if( *x + 2 < CHESS_SIZE && *y + 1 < CHESS_SIZE && chess[*x+2][*y+1] == 0 ){*x += 2;*y += 1;return 1;}break;case 6:if( *x + 2 < CHESS_SIZE && *y - 1 >= 0 && chess[*x+2][*y-1] == 0 ){*x += 2;*y -= 1;return 1;}break;case 7:if( *x + 1 < CHESS_SIZE && *y - 2 >= 0 && chess[*x+1][*y-2] == 0 ){*x += 1;*y -= 2;return 1;}break;case 8:if( *x - 1 >= 0 && *y - 2 >= 0 && chess[*x-1][*y-2] == 0 ){*x -= 1;*y -= 2;return 1;}break;default:break;}return 0;}int horseStepBoard(int x, int y, int step){int flag = 0, counter = 1;int x1 = x;int y1 = y;chess[x][y] = step;//已经走到stepif( CHESS_SIZE * CHESS_SIZE == step )return 1;//遍历结束,任务完成//还没有结束的话,找step的下一步在哪里flag = getNextPosition(&x1,&y1,counter);while( flag == 0 && counter <= 8 ){counter++;flag = getNextPosition(&x1, &y1, counter);}//如果找到next,则x1, y1的值会被改变。若没有找到,不执行下面的while,//说明x和y的值不合适,即周围至多的8个位置都不合适,将chess[i][j]还原//为0,跳出本层递归至代码90行,并且携带返回值0;在上层递归中找(x,y)//的nextPositionwhile( flag ){//找到了下一步if( horseStepBoard(x1, y1, step+1) == 1 )return 1;x1 = x;y1 = y;flag = getNextPosition(&x1, &y1, counter++);while( flag == 0 && counter <= 8 ){counter++;flag = getNextPosition(&x1, &y1, counter);}}if( flag == 0 ){chess[x][y] = 0;return 0;}}void PrintChess(){int i, j;for(i = 0; i < CHESS_SIZE; i++){for(j = 0; j < CHESS_SIZE; j++)printf("%5d", chess[i][j]);printf("\n\n");}}int main(){clock_t start, finish;start = clock();horseStepBoard(2,0,1);PrintChess();finish = clock();printf("running time is %fs\n", (double)(finish - start)/(CLOCKS_PER_SEC));return 0;}

0 0
原创粉丝点击