001    package aima.search.nqueens;
002    
003    import java.util.ArrayList;
004    import java.util.List;
005    
006    import aima.basic.XYLocation;
007    import aima.search.framework.Successor;
008    import aima.search.framework.SuccessorFunction;
009    
010    /**
011     * @author Ravi Mohan
012     * 
013     */
014    public class NQueensSuccessorFunction implements SuccessorFunction {
015    
016            public List getSuccessors(Object state) {
017                    List<Successor> successors = new ArrayList<Successor>();
018                    NQueensBoard board = (NQueensBoard) state;
019                    int numQueens = board.getNumberOfQueensOnBoard();
020                    int boardSize = board.getSize();
021                    for (int i = 0; i < boardSize; i++) {
022                            if (!(board.isSquareUnderAttack(new XYLocation(numQueens, i)))) {
023                                    NQueensBoard child = placeQueenAt(numQueens, i, board);
024                                    successors.add(new Successor("placeQueenAt " + numQueens + "  "
025                                                    + i, child));
026    
027                            }
028    
029                    }
030    
031                    return successors;
032            }
033    
034            private NQueensBoard placeQueenAt(int row, int column,
035                            NQueensBoard parentBoard) {
036    
037                    NQueensBoard newBoard = new NQueensBoard(parentBoard.getSize());
038                    List<XYLocation> queenPositionsOnParentBoard = parentBoard
039                                    .getQueenPositions();
040                    queenPositionsOnParentBoard.add(new XYLocation(row, column));
041                    newBoard.setBoard(queenPositionsOnParentBoard);
042                    return newBoard;
043            }
044    
045    }