• 八皇后问题


      //八皇后问题   回溯算法
        class Program
        {
            //初始化一个二维数组
            public static int Row = 8;
            public static int Col = 8;
            public static int[,] maps = new int[8, 8];
            public static int  count=0;
    
            //如何去放皇后
    
            public static void PutQueen(int row)
            {
                //递归出口
                if (row == Row)
                {
                    //打印八皇后的摆法
                    PrintQueen();
                    return;
                }
    
    
                for (int i = 0; i < Col; i++)
                {
                    if (IsKO(row, i))
                    {
                        //将皇后放在该点
                        maps[row, i] = 8;
                        //递归去放皇后
                        PutQueen(row+1);
                        //回溯
                        maps[row, i] = 0;
                     
                    }
                }
            }
            public static void PrintQueen()
            {
                Console.WriteLine("********************");
                count++;
               
                Console.WriteLine("第{0}中摆法,",count);
                for (int i = 0; i < Row; i++)
                {
                    for (int j = 0; j < Col; j++)
                    {
                        Console.Write(" "+maps[i, j]);
                    }
                    Console.WriteLine();
                }
            }
    
    
    
    
            //改行,行列,
            //如果把皇后方法到(x,y)点,则需要判断该点是否可以放
    
    
            public static bool IsKO(int x, int y)
            {
                //遍历二维数组,判断该行,列,正斜边,逆斜边是否存在皇后
                for (int i = 0; i < Row; i++)
                {
                    for (int j = 0; j < Col; j++)
                    {
                       //判断该行,列,正斜边,逆斜边是否存在皇后
                        //正斜边  x-y等于恒定值
                        // 逆斜边 x+y
                        //行  i==x   列 j==y
    
                        if (i == x || j == y || i - j == x - y||  i+j==x+y)
                        {
                            if (maps[i, j] == 8) //如果该点放了一个皇后,则返回false
                            {
                                return false;
                            }
                        }
                    }
                }
                return true;
            }
            static void Main(string[] args)
            {
    
    
                PutQueen(0);
                Console.ReadKey();
            }
        }
  • 相关阅读:
    使用XE7并行库中的TTask(转)
    Delphi xe7并行编程快速入门(转)
    Pre-compile (pre-JIT) your assembly on the fly, or trigger JIT compilation ahead-of-time (转)
    使用RemObjects Pascal Script (转)
    Remobjects SDK 服务器搭建
    toString()方法
    环境变量
    jstl标签学习
    SQL的各种join
    Mybatis的一些配置
  • 原文地址:https://www.cnblogs.com/tianranhui/p/10731026.html
Copyright © 2020-2023  润新知