Given krooks and a chessboard n by n, rooks can be safely placed on the board in Wvarious ways, where
W = k!(n C k)^2
written differently W = n!n!/(k!(n-k)!(n-k)!)
STATEMENT OF THE PROBLEM:
Write a program that will work on a chessboard n by nand count all the ways that kyou can use markers on a chessboard.
MY RESEARCH:
After searching the Internet, I finally found the code nQueensSolutionon Geekviewpoint , and I modify it as shown below. However, my code only works when k = n. Does anyone have an idea how to solve this for k<n?
Here is my code:
static int kRooksPermutations(int[] Q, int col, int k, int kLimit) {
int count = 0;
for (int x = 0; x < Q.length && col < Q.length; x++)
if (safeToAdd(Q, x, col)) {
if (k == kLimit - 1) {
count++;
Q[col] = -1;
} else {
Q[col] = x;
count += kRooksPermutations(Q, col + 1, k + 1, kLimit);
}
}
return count;
}
static boolean safeToAdd(int[] Q, int r, int c) {
for (int y = 0; y < c; y++)
if (Q[y] == r)
return false;
return true;
}
Here is the test code
public static void main(String... strings) {
kRooksPermutations(8,5);
}
source
share