用DFS解决八皇后问题(递归)(c#)

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

namespace EightQueenRecursive
{
    class Program
    {
        //定义棋盘
        int[] a = new int[8];
        //定义解决方案个数
        int solution=0;
        //规则
        public bool isOK(int row,int col)
        {
            for(int i = 0; i < row; i++)
            {
                if (a[i] == col||Math.Abs(a[i]-col)==Math.Abs(i-row))
                {
                    return false;
                }
            }
            return true;
            
        }
        //显示
        void display()
        {
            Console.WriteLine("第{0}种解", solution++);
            for (int i = 0; i < 8; i++)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (a[i] == j)
                    {
                        Console.Write("Q");
                    }else
                    {
                        Console.Write("#");
                    }
                }
                Console.WriteLine();
            }
            Console.WriteLine("--------");
        }
        void DSF(int row)
        {



            //find
            for (int i = 0; i < 8; i++)
            {
                if (isOK(row,i))
                {
                    a[row] = i;
                    if (row<7)
                    {
                        //forward
                        DSF(row + 1);
                    }
                    else
                    {
                        //done
                        display();
                    }
               
                }
                else
                {

                }
            }
        
        //back
     
        } 

        static void Main(string[] args)
        {
            Program p = new Program();
            //初始化棋盘
            foreach(int i in p.a)
            {
                p.a[i] = 0;
            }
            p.DSF(0);
            Console.ReadKey();
        }
    }
}

你可能感兴趣的:(用DFS解决八皇后问题(递归)(c#))