⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 eightqueen.cs

📁 利用C#语言实现的八皇后问题。只有8*8的棋盘形式
💻 CS
字号:
using System;
using System.Collections.Generic;
using System.Text;

namespace EightQueens
{
    public class EightQueen
    {
        bool IsSafe(int col,int row,int[] queenList)
        {
            //只检查前面的列
            for (int tempCol = 0; tempCol < col; tempCol++)
            {
                int tempRow = queenList[tempCol];
                if (tempRow == row)
                {
                    //同一行
                    return false;
                }
                if (tempCol == col)
                {
                    //同一列
                    return false;
                }
                if (tempRow - tempCol == row - col || tempRow + tempCol == row + col)
                {
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// 在第col列寻找安全的row值
        /// </summary>
        /// <param name="queenList"></param>
        /// <param name="col"></param>
        /// <returns></returns>
        public bool PlaceQueue(int[] queenList, int col)
        {
            int row = 0;
            bool foundSafePos = false;
            if (col == 8) //结束标志
            {
                //当处理完第8列的完成
                foundSafePos = true;
            }
            else
            {
                while (row < 8 && !foundSafePos)
                {
                    if (IsSafe(col, row, queenList))
                    {
                        //找到安全位置
                        queenList[col] = row;
                        //找下一列的安全位置
                        foundSafePos = PlaceQueue(queenList, col + 1);
                        if (!foundSafePos)
                        {
                            row++;
                        }
                    }
                    else
                    {
                        row++;
                    }
                }
            }
            return foundSafePos;
        }
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -