常用算法(C#):八皇后问题

八皇后问题: 八个皇后在排列时不能同在一行、一列或一条斜线上。

在8!=40320种排列中共有92种解决方案

 

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

namespace ExQueen
{
    class Queen
    {
        public void QueenArithmetic(int size)
        {
            int[] Queen = new int[size];//每行皇后的位置
            int y, x, i, j, d, t = 0;
            y = 0;
            Queen[0] = -1;
            while (true)
            {
                for (x = Queen[y] + 1; x < size; x++)
                {
                    for (i = 0; i < y; i++)
                    {
                        j = Queen[i];
                        d = y - i;
                        //检查新皇后是否能与以前的皇后相互攻击
                        if ((j == x) || (j == x - d) || (j == x + d))
                            break;
                    }
                    if (i >= y)
                        break;//不攻击
                }
                if (x == size) //没有合适的位置
                {
                    if (0 == y)
                    {
                        //回朔到了第一行
                        Console.WriteLine("Over");
                        break; //结束
                    }
                    //回朔
                    Queen[y] = -1;
                    y--;
                }
                else
                {
                    Queen[y] = x;//确定皇后的位置
                    y++;//下一个皇后
                    if (y < size)
                        Queen[y] = -1;
                    else
                    {
                        //所有的皇后都排完了,输出
                        Console.WriteLine("\n" + ++t + ':');
                        for (i = 0; i < size; i++)
                        {
                            for (j = 0; j < size; j++)
                                Console.Write(Queen[i] == j ? 'Q' : '*');
                            Console.WriteLine();
                        }
                        y = size - 1;//回朔
                    }
                }
            }
        }
        public static void Main()
        {
            int size = 8;//皇后数
            Queen q = new Queen();
            q.QueenArithmetic(size);
        }
    }
}

你可能感兴趣的:(八皇后)