Given k rooks and a n by n chess board, the rooks can safely be placed on the board W different ways, where
W = k!(n C k)^2
written differently W = n!n!/(k!(n-k)!(n-k)!)
PROBLEM STATEMENT:
Write a program that will run over a n by n chessboard and count all the ways that k rooks can safely be placed on the board.
MY RESEARCH:
After searching the internet I finally find a nQueensSolution code on Geekviewpoint and I modify it as 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 a test code
public static void main(String... strings) {
kRooksPermutations(8,5);
}
Got it!
Prints: