C# 解决八皇后问题

举报
陈言必行 发表于 2021/08/14 00:52:52 2021/08/14
【摘要】 八皇后问题: class Bahuanghou{static void Main(string[] args) { Console.ReadLine(); ChessSort(0, newint[8]); Console.ReadLine();} public static bool Compare(int lastChess, intdiffe...
八皇后问题:

    
  1. class Bahuanghou{
  2. static void Main(string[] args) {
  3. Console.ReadLine();
  4. ChessSort(0, newint[8]);
  5. Console.ReadLine();
  6. }
  7. public static bool Compare(int lastChess, intdifference, int nowChess)
  8. {
  9. if(lastChess == nowChess || lastChess - nowChess == difference ||nowChess - lastChess == difference)
  10. {
  11. return false;
  12. }
  13. else
  14. {
  15. return true;
  16. }
  17. }
  18. public static void Write(int[] Chesses)//输出结果
  19. {
  20. for (int i= 0; i < 8; i++)
  21. {
  22. Console.Write(Chesses[i]);//输出结果是皇后所在的位置
  23. }
  24. Console.Write("\n");
  25. }
  26. public static bool Conflict(int row, int Chess,int[] Chesses)
  27. {
  28. if (row ==0)
  29. {
  30. return false;
  31. }
  32. else
  33. {
  34. for (int n = 0; n < row;n++)
  35. {
  36. if (!Compare(Chesses[n], row - n, Chess))
  37. {
  38. returntrue;
  39. }
  40. }
  41. return false;
  42. }
  43. }
  44. public static void ChessSort(int num, int[]Chesses)
  45. {
  46. for (int j= 1; j < 9; j++)
  47. {
  48. if (num == 8)
  49. {
  50. Write(Chesses);
  51. break;
  52. }
  53. if (!Conflict(num, j,Chesses))
  54. {
  55. Chesses[num] = j;
  56. ChessSort(num + 1, Chesses);
  57. }
  58. }
  59. }


文章来源: czhenya.blog.csdn.net,作者:陈言必行,版权归原作者所有,如需转载,请联系作者。

原文链接:czhenya.blog.csdn.net/article/details/76092019

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。