常用演算法(C#):八皇后問題

來源:互聯網
上載者:User

八皇后問題: 八個皇后在排列時不能同在一行、一列或一條斜線上。

在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);
        }
    }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.