dfs:马踏棋盘
1 #include<stdio.h> 2 #include<time.h> 3 4 #define X 8 5 #define Y 8 6 7 int chess[X][Y]; 8 9 //查找当前位置的下一个位置 10 int nextxy(int* x, int* y, int count) 11 { 12 switch (count) 13 { 14 case 0: 15 if (*x + 2 <= X - 1 && *y - 1 >= 0 && chess[*x + 2][*y - 1] == 0) 16 { 17 *x += 2; 18 *y -= 1; 19 return 1; 20 } 21 break; 22 23 case 1: 24 if (*x + 2 <= X - 1 && *y + 1 <= Y - 1 && chess[*x + 2][*y + 1] == 0) 25 { 26 *x += 2; 27 *y += 1; 28 return 1; 29 } 30 break; 31 32 case 2: 33 if (*x + 1 <= X - 1 && *y + 2 <= Y - 1 && chess[*x + 1][*y + 2] == 0) 34 { 35 *x += 1; 36 *y += 2; 37 return 1; 38 } 39 break; 40 41 case 3: 42 if (*x - 1 >= 0 && *y + 2 <= Y - 1 && chess[*x - 1][*y + 2] == 0) 43 { 44 *x -= 1; 45 *y += 2; 46 return 1; 47 } 48 break; 49 50 case 4: 51 if (*x - 2 >= 0 && *y + 1 <= Y - 1 && chess[*x - 2][*y + 1] == 0) 52 { 53 *x -= 2; 54 *y += 1; 55 return 1; 56 } 57 break; 58 59 case 5: 60 if (*x - 2 >= 0 && *y - 1 >= 0 && chess[*x - 2][*y - 1] == 0) 61 { 62 *x -= 2; 63 *y -= 1; 64 return 1; 65 } 66 break; 67 68 case 6: 69 if (*x - 1 >= 0 && *y - 2 >= 0 && chess[*x - 1][*y - 2] == 0) 70 { 71 *x -= 1; 72 *y -= 2; 73 return 1; 74 } 75 break; 76 77 case 7: 78 if (*x + 1 <= X - 1 && *y - 2 >= 0 && chess[*x + 1][*y - 2] == 0) 79 { 80 *x += 1; 81 *y -= 2; 82 return 1; 83 } 84 break; 85 default: 86 break; 87 } 88 89 return 0; 90 } 91 92 void print() 93 { 94 int i, j; 95 for (i = 0; i < X; i++) 96 { 97 for (j = 0; j < Y; j++) 98 { 99 printf("%2d\t", chess[i][j]); 100 } 101 printf("\n"); 102 } 103 104 printf("\n"); 105 } 106 107 //深度优先遍历 108 //(x,y)为位置坐标 109 //tag为标记变量,每走一步,tag+1 110 int TravelChessBoard(int x, int y, int tag) 111 { 112 int x1 = x; 113 int y1 = y; 114 int flag = 0; 115 int count = 1; 116 chess[x][y] = tag; 117 118 if (tag == X * Y) 119 { 120 //打印棋盘 121 print(); 122 return 1; 123 } 124 //找到马的下一个可走坐标(x1,y1),如果找到flag = 1,否则为0 125 flag = nextxy(&x1, &y1, count); 126 while (flag == 0 && count < 8) 127 { 128 count++; 129 flag = nextxy(&x1, &y1, count); 130 } 131 132 133 while (flag) 134 { 135 if (TravelChessBoard(x1, y1, tag + 1)) 136 { 137 return 1; 138 } 139 140 //继续找到马的下一步的可走的坐标(x1,y1),如果找到flag = 1,否则为0 141 x1 = x; 142 y1 = y; 143 count++; 144 145 flag = nextxy(&x1, &y1, count); 146 while (flag == 0 && count < 8) 147 { 148 count++; 149 flag = nextxy(&x1, &y1, count); 150 } 151 } 152 153 if (flag == 0) 154 { 155 chess[x][y] = 0; 156 } 157 158 return 0; 159 } 160 161 int main() 162 { 163 int i, j; 164 clock_t start, finish; 165 166 start = clock(); 167 168 for (i = 0; i < X; i++) 169 { 170 for (j = 0; j < Y; j++) 171 { 172 chess[i][j] = 0; 173 } 174 } 175 176 printf("下面开始马踏棋盘:\n"); 177 if (!TravelChessBoard(1, 0, 1)) 178 { 179 printf("马踏棋盘失败了\n"); 180 } 181 182 finish = clock(); 183 printf("\n本次计算义工耗时:%f\n\n", (double)(finish - start) / CLOCKS_PER_SEC); 184 185 return 0; 186 }
程序没问题,但是再vs上运行了好久也没运行出来