Eight Queens

Challenge

Using the C# language, have the function  EightQueens(strArr) read  strArr which will be an array consisting of the locations of eight Queens on a standard 8x8 chess board with no other pieces on the board. The structure of  strArr will be the following: ["(x,y)", "(x,y)", ...] where (x,y) represents the position of the current queen on the chessboard (x and y will both range from 1 to 8 where 1,1 is the bottom-left of the chessboard and 8,8 is the top-right). Your program should determine if all of the queens are placed in such a way where none of them are attacking each other. If this is true for the given input, return the string  true otherwise return the first queen in the list that is attacking another piece in the same format it was provided. 

For example: if  strArr is ["(2,1)", "(4,2)", "(6,3)", "(8,4)", "(3,5)", "(1,6)", "(7,7)", "(5,8)"] then your program should return the string  true. The corresponding chessboard of queens for this input is below (taken from  Wikipedia). 

 
Sample Test Cases

Input:"(2,1)", "(4,3)", "(6,3)", "(8,4)", "(3,4)", "(1,6)", "(7,7)", "(5,8)"

Output:"(2,1)"


Input:"(2,1)", "(5,3)", "(6,3)", "(8,4)", "(3,4)", "(1,8)", "(7,7)", "(5,8)"

Output:"(5,3)"


Eight Queens算法

1、一个 8 x 8 棋盘格[左下角->(1,1);右上角->(8,8)],输入一系列坐标(表示皇后在棋盘格位置);

2、判断每个皇后是否处于未攻击位置,如果是,返回true;否则返回第一个被攻击皇后的坐标

        public static string EightQueens(string[] strArr)
        {
            Regex mRegex = new Regex("[a-zA-Z0-9]+");
            MatchCollection mMactchCol;
            int[,] intArray = new int[strArr.Length, 2];
            int num = 0;
            for (int i = 0; i < strArr.Length; i++)
            {
                mMactchCol = mRegex.Matches(strArr[i]);
                num = 0;
                foreach (Match item in mMactchCol)
                {
                    intArray[i, num++] = Convert.ToInt32(item.Value);
                }
            }

            for (int i = 0; i < strArr.Length; i++)
            {
                for (int j = i + 1; j < strArr.Length; j++)
                {
                    if ((intArray[i, 0] - intArray[j, 0] == intArray[i, 1] - intArray[j, 1])/*对角线*/
                        || (intArray[i, 0] - intArray[j, 0] == intArray[j, 1] - intArray[i, 1])/*对角线*/
                        || (intArray[i, 0] == intArray[j, 0] || intArray[i, 1] == intArray[j, 1])/*直线*/)
                    {
                        return strArr[i];
                    }
                }
            }
            return "true";
        }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值