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).
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).
![](http://i.imgur.com/zAT24ML.png)
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";
}