深圳幻海软件技术有限公司 欢迎您!

C语言 八皇后问题的解决

2023-03-28

八皇后的问题描述:   在8X8方格的棋盘中,每一行中有一个皇后旗子,该旗子的横、 竖、左倾斜、右倾斜的位置都是不能存在其他的旗子,问有多少种摆法?百度百科介绍解决的思路  1. 固定到一行,依次选择下一列  

八皇后的问题描述:

     在 8 X 8 方格的棋盘中 ,每一行 中 有一个皇后旗子, 该旗子的 横、 竖、左倾斜、右倾斜的位置都是不能存在其他的旗子, 问有多少种摆法?

百度百科介绍

解决的思路

   1. 固定到一行,依次选择下一列

   2. 当选择一个位置的时候,需要 判断 该棋子位置的行方向 列方向 对角倾斜的方向 有没有其他的棋子, 如果有,则 换下对应列的位置

解决代码如下

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int count = 1;
  4. // 判断当前的位置 是否危险
  5. // 0 是危险
  6. // 1 不危险
  7. // row 是当前的行 y
  8. // column 当前的列 x
  9. int isExistChess(int row, int column, int (*chess)[8]){
  10. int z;
  11. int x3 = row, y3 = column;
  12. int x4 = row, y4 = column;
  13. // 正上
  14. for(z = row; z >= 0; z--){
  15. if(chess[z][column] == 1){
  16. return 0;
  17. }
  18. }
  19. // 正左
  20. // for(z = column; z >= 0; z--){
  21. // if(chess[row][z] == 1){
  22. // return 0;
  23. // }
  24. // }
  25. // 左上
  26. while(x3 >= 0 && y3 >= 0){
  27. if(chess[x3][y3] == 1){
  28. return 0;
  29. }
  30. x3 -= 1;
  31. y3 -= 1;
  32. }
  33. // 右上
  34. while(x4 >= 0 && y4 < 8){
  35. if(chess[x4][y4] == 1){
  36. return 0;
  37. }
  38. x4 -= 1;
  39. y4 += 1;
  40. }
  41. return 1;
  42. }
  43. void ChessErgodic(int row, int (*chess)[8]){
  44. int tmpchess[8][8], x, y;
  45. for(x = 0; x < 8; x++){
  46. for(y = 0; y < 8; y++){
  47. *(*(tmpchess + x) + y) = *(*(chess + x) + y);
  48. }
  49. }
  50. if(8 == row){
  51. printf("第%d种:\n", count++);
  52. for(x = 0; x < 8; x++){
  53. for(y = 0; y < 8; y++){
  54. printf("%d ", *(*(tmpchess + x) + y));
  55. }
  56. printf("\n");
  57. }
  58. printf("\n");
  59. } else {
  60. for(y = 0; y < 8; y++){
  61. for(x = 0; x < 8; x++){
  62. *(*(tmpchess + row) + x) = 0;
  63. }
  64. if(isExistChess(row, y, tmpchess)){
  65. *(*(tmpchess + row) + y) = 1;
  66. ChessErgodic(row + 1, tmpchess);
  67. }
  68. }
  69. }
  70. }
  71. int main(int argc, char const *argv[])
  72. {
  73. int chess[8][8], x, y;
  74. // 初始化棋盘
  75. for(x = 0; x < 8; x++){
  76. for(y = 0; y < 8; y++){
  77. chess[x][y] = 0;
  78. }
  79. }
  80. ChessErgodic(0, chess);
  81. return 0;
  82. }

结果:

  1. ...
  2. 92种:
  3. 0 0 0 0 0 0 0 1
  4. 0 0 0 1 0 0 0 0
  5. 1 0 0 0 0 0 0 0
  6. 0 0 1 0 0 0 0 0
  7. 0 0 0 0 0 1 0 0
  8. 0 1 0 0 0 0 0 0
  9. 0 0 0 0 0 0 1 0
  10. 0 0 0 0 1 0 0 0

可以看出,总共有 92 中摆放方法 ,高斯先生都算不全的东西,使用编程就能很好的解决

文章知识点与官方知识档案匹配,可进一步学习相关知识
C技能树首页概览135566 人正在系统学习中