首页 > 学院 > 开发设计 > 正文

C#递归求解八皇后

2019-11-17 04:20:19
字体:
来源:转载
供稿:网友

C#递归求解八皇后,废话不说了,直接看代码吧。

view plaincopy to clipboardPRint?
using System;  
using System.Collections.Generic;  
using System.Text;  
 
namespace Queen  
{  
    /* 
     * 八皇后问题 
     * @Author: Red_angelX 
     */ 
    class Program  
    {  
        const int NCOUNT = 8;  
 
        static int[] QueenMap = new int[NCOUNT];  
 
        static int iCount = 1;  
 
        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.Write(" ");  
        }  
 
        /* 
         * 检查第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;  
        }  
    }  

http://blog.csdn.net/gisfarmer/archive/2009/02/03/3860266.aspx


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表