欢迎访问我的博客 https://javascript.shop

递归 八皇后问题

原文发布时间为:2009-03-04 —— 来源于本人的百度文章 [由搬家工具导入]

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

namespace digui1
{
    public class Class4//八皇后
    {
        public static char[,] queen = new char[8, 8];
        public static int[] a = new int[8];
        public static int[] b = new int[15];
        public static int[] c = new int[15];
        public static int num = 0;

        public static void Main()
        {
            for (int i = 0; i < 8; i++)
                for (int j = 0; j < 8; j++)
                    queen[i, j] = '*';
            fun(0);
            Console.ReadLine();
        }

        public static void fun(int i)
        {
            int iColum;
            for (iColum = 0; iColum < 8; iColum++)
            {
                if (a[iColum] == 0 && b[i - iColum + 7] == 0 && c[i + iColum] == 0)
                {
                    queen[i, iColum] = ;
                    a[iColum] = 1;
                    b[i - iColum + 7] = 1;
                    c[i + iColum] = 1;
                    if (i < 7)
                        fun(i + 1);
                    else
                    {
                        Console.WriteLine("第{0}种状态为:", ++num);
                        for (int j = 0; j < 8; j++)
                        {
                            for (int k = 0; k < 8; k++)
                                Console.Write("{0}", queen[j, k]);
                            Console.WriteLine();
                        }
                    }
                    queen[i, iColum] = '*';
                    a[iColum] = 0;
                    b[i - iColum + 7] = 0;
                    c[i + iColum] = 0;
                }
            }
        }
    }
}

posted @ 2017-07-12 00:05  孑孓子  阅读(102)  评论(0编辑  收藏  举报
欢迎访问我的博客 https://javascript.shop