[英]Find out the Number of ways in which two queens intersects (won't be stable) on n*n chessboard?
我可以使用組合來做到這一點。 如果皇后區處於同一位置,它們將不穩定 (受到攻擊):
所以
n * P(n,2)
n * P(n,2)
2 * ( P(n,2) + P(n-1,2) + ... + P(2,2)) + 2 * (P(n-1,2) + ... + P(2,2))
對於上述情況,什么是合適的算法?
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
int n = 8;
int arr[][] = new int[n][n];
long x = 0;
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
x += Math.min(n-1-i, n-1-j) + Math.min(i, j) + Math.min(n-1-i,j) + Math.min(i,n-1-j);
x+= 2*n -2;
}
}
System.out.println(x);
}
}
上面的邏輯怎么樣?
好吧,對於n * n
板,有
All: n * n * (n * n - 1) / 2
Stable: n * (n - 1) * (n - 2) * (3 * n - 1) / 6
Unstable: n * (5 * n - 1) * (n - 1) / 3
職位。 (有關詳細信息,請參見https://oeis.org/A036464 )。 小n
的一些示例:
n all unstable stable
-----------------------------
1 0 = 0 + 0
2 6 = 6 + 0
3 36 = 28 + 8
4 120 = 76 + 44
5 300 = 160 + 140
6 630 = 290 + 340
7 1176 = 476 + 700
8 2016 = 728 + 1288
9 3240 = 1056 + 2184
10 4950 = 1470 + 3480
實現(Java)很明顯
private static long unstableCount(long n) {
return n * (5 * n - 1) * (n - 1) / 3;
}
可能有趣的是,
All = O(n**4)
Stable = O(n**4)
Unstable = O(n**3) // just cube
因此,對於大板,幾乎所有位置都是穩定的。
如果皇后區分開來 (例如,您有白色和紅色皇后區),您要做的就是將上面的數字和公式乘以 2
(交換皇后區將帶來一個新的位置)。
private static long unstableDistinguishableCount(long n) {
return n * (5 * n - 1) * (n - 1) / 3 * 2;
}
編輯 :天真的采樣實現(我們循環所有可能的皇后位置)
private static long unstableCountNaive(int n) {
long result = 0;
for (int file1 = 0; file1 < n; ++file1)
for (int rank1 = 0; rank1 < n; ++rank1)
for (int file2 = file1; file2 < n; ++file2)
for (int rank2 = file1 == file2 ? rank1 + 1 : 0; rank2 < n; ++rank2)
if ((file1 == file2) || // Same file
(rank1 == rank2) || // Same rank
(file1 + rank1 == file2 + rank2) || // Same top-left bottom-right diagonal
(file1 - rank1 == file2 - rank2)) // Same bottom-left top-right diagonal
result += 1;
return result;
}
編輯2 :如果我的想法正確,則可以只計算對角線攻擊,然后使用對稱性:
private static long unstableCountBetter(int n) {
long result = 0;
// Attacked by top-left bottom-right diagonal
for (int rank = 0; rank < n; ++rank)
for (int file = 0; file < n; ++file)
result +=
(rank + file >= n ? 2 * n - 2 - (rank + file) : rank + file);
result =
// symmetry: we have TWO diagonals
result * 2 +
// At each postion (n * n of them) we have n - 1 checks on the same rank
n * n * (n - 1) +
// At each postion (n * n of them) we have n - 1 checks on the same file
n * n * (n - 1);
// /2 if queens are indistiguished (728 for 8x8 board)
return result / 2;
}
這個問題有點不完整,但是看評論,我想我已經掌握了所有信息來回答這個問題。
由於您寫道2個皇后在3 * 3板上有56種相交的方式,因此您將兩個皇后視為不同,即。 下令。 例如。 這兩個板不同:
..q ..Q
.Q. .q.
... ...
因此,您的問題的答案是n * n板的簡單公式:
(n*n) * (n*n - 1) - n*(n-1)*(n-2)*(3*n-1)/3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.