zoukankan      html  css  js  c++  java
  • 回溯算法之8皇后问题

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace SeqListSort
    {
        /// <summary>
        /// 8皇后算法
        /// <ather>
        /// <lihonglin>
        /// </ather>
        /// </summary>
        class EightQueen
        {
            private const int COL = 8;//
            private const int ROW = 8;
            private static int[,] map = new int[COL, ROW];// 棋盘
            private static int Count = 0;// 摆放皇后位置的种数
    
            // 放置皇后
            public static void PutQueen(int row)
            {
                int i = 0;
                if (ROW == row)//结束条件
                {
                    Display();
                    return;
                }
    
                // 一列一列摆放
                for (i = 0; i < COL; ++i )
                {
                    if (IsOK(row, i))
                    {
                        map[row, i] = 8;
                        PutQueen(row+1);
                        // 回溯
                        map[row, i] = 0;
                    }
                }
            }
            // 摆放规则
            public static bool IsOK(int x, int y)
            {
                for (int i = 0; i < COL; i++)
                {
                    for (int j = 0; j < ROW; ++j)
                    {
                        //摆放规则,同一行,同一列,该位置的斜边和逆斜边都不能放
                       if (i == x || j == y || (x + y == i + j) || ( x - y == i - j))
                       {
                            if (8 == map[i,j])
                            {
                                return false;
                            }
                           
                       }
    
                    }
                }
                return true;
            }
    
            public static void Display()
            {
                Count++;
                Console.WriteLine (" 第{0}种 " , Count);
                for (int i = 0; i < COL; i++)
                {
                    for (int j = 0; j < ROW; ++j)
                    {
                        
                        Console.Write( "  "+ map[i,j] );
                    }
                    Console.WriteLine();
                }
            }
        }
    }
  • 相关阅读:
    php RSA公钥私钥加解密和验证用法
    php格式化RSA公钥私钥字符串
    你的周末时光是什么样的?
    php-redis 消息订阅笔记
    php redis 常用操作
    MySql索引笔记
    yii1框架,事务使用方法
    python 项目打包成exe可执行程序
    Linux修改默认端口
    C++字符串作为参数的传递
  • 原文地址:https://www.cnblogs.com/lihonglin2016/p/4307867.html
Copyright © 2011-2022 走看看