1
試圖在N*N
板上修改騎士運動套裝的N-Queens
算法。在我的情況下,我正在使用4*4
和8*8
板進行測試。N-Queens算法。劇情扭曲:女王也是騎士
我的算法,我的遞歸失敗處理騎士,因爲它有時需要跳過一行。如果只是Queens的運動,則不需要跳過行,因爲每行的女王號確切爲1
。
問題出在我的Solve()
函數中,因爲我的遞歸關係與皇后的數量有關。通常每塊板的皇后數量應該是8
。然而,結合騎士運動減少到6
。因此,我認爲遞歸沒有足夠深入(只有6行深,而不是8)。
例如在4*4
板的溶液是(1,1)
和(4,2)
(行*列)。但它不能跳過第2行和第3行。
如何使遞歸查看所有行,同時能夠跳過一些行。
static int[] board = new int[9];
static int cnt = 0;
static bool CanPlace(int row, int col) // eg. x[1] = 2, 1st row 2nd col has a Queen
{
for (int j = 1; j <= (row - 1); j++)
{
if (board[j] == col || Math.Abs(board[j] - col) == Math.Abs(j - row)) return false;
if ((Math.Abs(board[j] - col) - 1) == Math.Abs(j - row)) return false;
//The line of code above should work for all of the possible moves of the Knight.
//At least it does for a 4x4 board, for the first two lines.
//Giving a pair of results = (1,1)(2,4) and the mirror (1,4)(2,1)
}
return true;
}
static void Solve(int row, int boardSize)
{
for (int col = 1; col <= boardSize; col++)
{
if (CanPlace(row, col)) //This only triggers 6 times per board
{
board[row] = col;
if (row == boardSize - 2) // Here i tried to fix it but the bottom rows get sacrificed
PrintBoard();
else
Solve(row + 1, boardSize);
}
}
}
static void PrintBoard()
{
Console.WriteLine();
cnt++;
for (int i = 1; i <= board.Length-1; i++)
{
for (int j = 1; j <= board.Length - 1; j++)
if (board[i] == j) Console.Write("Q");
else Console.Write(".");
Console.WriteLine();
}
for (int i = 1; i <= board.Length - 1; i++)
Console.Write("{0},", board[i]);
Console.WriteLine();
}
static void Main(string[] args)
{
Solve(1, 8);
Console.WriteLine("\nNumber of solutions: {0}\n",cnt);
}
我認爲第一步是要證明一個解決方案 – Steve
@Steve - 當返回的計數爲0 – Prune
不是這種殘酷的力量,雖然發生......解決初代N皇后是貪婪 – Steve