8Queue

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _8Queen
{
    class Program
    {
        const int NCOUNT = 8;

        static int[] QueenMap = new int[NCOUNT];

        static int iCount = 1;


        /* 
         * 核心函数,放置第N枚皇后(递归) 
         */
        static void Main(string[] args)
        {
            int current = System.Environment.TickCount;

            PlayQueen(0);

            Console.WriteLine("Eclped {0} ms", Environment.TickCount - current);
            Console.Read();
        }

        /* 
         * 核心函数,放置第N枚皇后(递归) 
         */
        static void PlayQueen(int n)
        {
            if (n == NCOUNT)
            {
                PrintResult();
                return;
            }

            for (int i = 1; i <= NCOUNT; i++)
            {
                QueenMap[n] = i;
                if (IsValid(n))
                    PlayQueen(n + 1);
            }

        }



        /* 
         * 输出结果 
         */
        static void PrintResult()
        {
            Console.Write("No.{0} ", iCount++);

            for (int i = 0; i < NCOUNT; i++)
                Console.Write("{0} ", QueenMap[i]);
            Console.WriteLine(" ");
        }

        /* 
         * 检查第n个皇后放上去之后是否合法 
         */
        static bool IsValid(int n)
        {
            for (int i = 0; i < n; i++)
            {
                if (QueenMap[i] == QueenMap[n])
                    return false;

                if (Math.Abs(QueenMap[i] - QueenMap[n]) == n - i)
                    return false;
            }
            return true;
        }

    }
}
原文地址:https://www.cnblogs.com/zzunstu/p/3438129.html