I need an algorithm to find out all the possible positions of a group of pieces in a chessboard. Like finding all the possible combinations of the positions of a number N of pieces.
For example in a chessboard numbered like cartesian coordinate systems any piece would be in a position
(x,y) where 1 <= x <= 8 and 1 <= y <= 8
I’d like to get an algorithm which can calculate for example for 3 pieces all the possible positions of the pieces in the board. But I don’t know how can I get them in any order. I can get all the possible positions of a single piece but I don’t know how to mix them with more pieces.
for(int i = 0; i<= 8; i++){
for(int j = 0; j<= 8; j++){
System.out.println("Position: x:"+i+", y:"+j);
}
}
How can I get a good algoritm to find all the posible positions of the pieces in a chessboard?
Thanks.
You got 8×8 board, so total of 64 squares.
Populate a list containing these 64 sqaures [let it be
list], and find all of the possibilities recursively: Each step will “guess” one point, and invoke the recursve call to find the other points.Pseudo code:
invoke with
choose(list,numPieces,[])wherelistis the pre-populated list with 64 elements, andnumPiecesis the pieces you are going to place.Note: This solution assumes pieces are not identical, so
[(1,2),(2,1)]and[(2,1),(1,2)]are both good different solutions.EDIT:
Just a word about complexity, since there are
(n^2)!/(n^2-k)!possible solutions for your problem – and you are looking for all of them, any algorithm will suffer from exponential run time, so trying to invoke it with just 10 pieces, will take ~400 years[In the above notation,
nis the width and length of the board, andkis the number of pieces]