public class Nqueen { private final int dim = 8; private final int queen = 1; private int[][] chessBoard = new int[dim][dim]; private int count = 0; private int startrow = 0; public void initialize() { setUpBoard(); solve(0); System.out.println("\n\nTOTAL NO. OF SOLUTIONS : " + count); } /* * This function checks whether a queen can be place in cell marked by (row,col) * If yes then returns true * Else returns false */ public boolean isSafe(int row, int col) { for(int i=0; i<dim ; i++) { if(chessBoard[i][col] == queen && i!= row) return false; if(chessBoard[row][i] == queen && i != col) return false; } //diagnol check int i = row-1 , j= col-1; while(i>=0 && j>=0) { if(chessBoard[i][j] == queen) return false; i--; j--; } i = row+1; j=col+1; while(i<dim && j<dim) { if(chessBoard[i][j] == queen) return false; i++; j++; } i= row-1; j = col+1; while(i>=0 && j<dim) { if(chessBoard[i][j] == queen) return false; i--; j++; } i = row+1; j = col-1; while(i<dim && j>=0) { if(chessBoard[i][j] == queen) return false; i++; j--; } return true; } /* * This function initialized board to all 0's */ public void setUpBoard() { for(int i=0; i<dim ; i++) { for(int j=0; j<dim ; j++) { chessBoard[i][j] = 0; } } } /* * This function place a queen at row, col position */ public void placeQueen(int row, int col) { chessBoard[row][col] = queen; } /* * This function removes a queen placed at row, col position */ public void removeQueen(int row, int col) { chessBoard[row][col] = 0; } /* * This function displays the chess board. */ public void displayChessBoard() { for(int i=0 ; i< dim ; i++) { System.out.println(); for(int j=0 ; j<dim ; j++) { System.out.print(chessBoard[i][j] + " "); } } } /* * This function uses backtracking approach and check all possible test cases. */ public void solve(int col) { if(col >= dim) { count++; System.out.println(); displayChessBoard(); return; } for(int row =startrow ; row<dim ; row++) { if(isSafe(row,col)) { placeQueen(row,col); solve(col+1); removeQueen(row,col); } } } public static void main(String args[]) { Nqueen n = new Nqueen(); n.initialize(); } }
Monday, 20 August 2012
N QUEEN PROBLEM: On a NxN board place N queens such that no queen is under attack where a queen can move any steps horizontally, vertically and diagnolly.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment