马踏棋盘问题
问题描述:将马随机放在国际象棋的Board[0~7][0~7]的某个方格中,马按走棋规则进行移动。走遍棋盘上全部64个方格并且不能重复。求出马的行走路线,并按求出的行走 路线,将数字1,2,…,64依次填入一个8×8的方阵,输出之。
1 #include<stdio.h> 2 #include<time.h> 3 4 #define CHESS_SIZE 5 5 6 int chess[CHESS_SIZE][CHESS_SIZE]; 7 8 int getNextPosition(int* x, int* y, int counter){ 9 switch(counter) 10 { 11 case 1: 12 if( *x - 2 >= 0 && *y - 1 >= 0 && chess[*x-2][*y-1] == 0 ){ 13 *x -= 2; 14 *y -= 1; 15 return 1; 16 } 17 break; 18 case 2: 19 if( *x - 2 >= 0 && *y + 1 < CHESS_SIZE && chess[*x-2][*y+1] == 0 ){ 20 *x -= 2; 21 *y += 1; 22 return 1; 23 } 24 break; 25 case 3: 26 if( *x - 1 >= 0 && *y + 2 < CHESS_SIZE && chess[*x-1][*y+2] == 0 ){ 27 *x -= 1; 28 *y += 2; 29 return 1; 30 } 31 break; 32 case 4: 33 if( *x + 1 < CHESS_SIZE && *y + 2 < CHESS_SIZE && chess[*x+1][*y+2] == 0 ){ 34 *x += 1; 35 *y += 2; 36 return 1; 37 } 38 break; 39 case 5: 40 if( *x + 2 < CHESS_SIZE && *y + 1 < CHESS_SIZE && chess[*x+2][*y+1] == 0 ){ 41 *x += 2; 42 *y += 1; 43 return 1; 44 } 45 break; 46 case 6: 47 if( *x + 2 < CHESS_SIZE && *y - 1 >= 0 && chess[*x+2][*y-1] == 0 ){ 48 *x += 2; 49 *y -= 1; 50 return 1; 51 } 52 break; 53 case 7: 54 if( *x + 1 < CHESS_SIZE && *y - 2 >= 0 && chess[*x+1][*y-2] == 0 ){ 55 *x += 1; 56 *y -= 2; 57 return 1; 58 } 59 break; 60 case 8: 61 if( *x - 1 >= 0 && *y - 2 >= 0 && chess[*x-1][*y-2] == 0 ){ 62 *x -= 1; 63 *y -= 2; 64 return 1; 65 } 66 break; 67 default: 68 break; 69 } 70 return 0; 71 } 72 int horseStepBoard(int x, int y, int step){ 73 int flag = 0, counter = 1; 74 int x1 = x; 75 int y1 = y; 76 chess[x][y] = step; //已经走到step 77 if( CHESS_SIZE * CHESS_SIZE == step ) 78 return 1; //遍历结束,任务完成 79 //还没有结束的话,找step的下一步在哪里 80 flag = getNextPosition(&x1,&y1,counter); 81 while( flag == 0 && counter <= 8 ){ 82 counter++; 83 flag = getNextPosition(&x1, &y1, counter); 84 } //如果找到next,则x1, y1的值会被改变。若没有找到,不执行下面的while, 85 //说明x和y的值不合适,即周围至多的8个位置都不合适,将chess[i][j]还原 86 //为0,跳出本层递归至代码90行,并且携带返回值0;在上层递归中找(x,y) 87 //的nextPosition 88 89 while( flag ){ //找到了下一步 90 if( horseStepBoard(x1, y1, step+1) == 1 ) 91 return 1; 92 x1 = x; 93 y1 = y; 94 flag = getNextPosition(&x1, &y1, counter++); 95 while( flag == 0 && counter <= 8 ){ 96 counter++; 97 flag = getNextPosition(&x1, &y1, counter); 98 } 99 } 100 101 if( flag == 0 ){ 102 chess[x][y] = 0; 103 return 0; 104 } 105 } 106 void PrintChess(){ 107 int i, j; 108 for(i = 0; i < CHESS_SIZE; i++){ 109 for(j = 0; j < CHESS_SIZE; j++) 110 printf("%5d", chess[i][j]); 111 printf("\n\n"); 112 } 113 } 114 int main(){ 115 clock_t start, finish; 116 start = clock(); 117 horseStepBoard(2,0,1); 118 PrintChess(); 119 finish = clock(); 120 printf("running time is %fs\n", (double)(finish - start)/(CLOCKS_PER_SEC)); 121 return 0; 122 }