Created
October 18, 2013 07:58
-
-
Save avanishgiri/7038011 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NQueens | |
{ | |
final static int N = 15; | |
private static boolean possibleQueen(boolean[][] board, int row, int column){ | |
for(int i = 0; i < N; i++) | |
if(board[row][i] && i != column) | |
return false; | |
for(int i = 0; i < N; i++) | |
if(board[i][column] && i != row) | |
return false; | |
for(int i = 0; i < N; i++){ | |
for(int j = 0; j < N; j++) { | |
if(i == row && j == column) | |
continue; | |
if(board[i][j]){ | |
if(row-i == column-j || i-row == column-j) | |
return false; | |
} | |
} | |
} | |
return true; | |
} | |
private static void printBoard(boolean[][] board){ | |
for(int i = 0; i < N; i++){ | |
for(int j = 0; j<N; j++){ | |
if(board[i][j]) | |
System.out.print("Q "); | |
else | |
System.out.print("_ "); | |
} | |
System.out.print("\n"); | |
} | |
System.out.print("\n"); | |
} | |
private static boolean solve(boolean[][] board, int column){ | |
if(column >= N) | |
return true; | |
for(int row = 0; row < N; row++) { | |
if(possibleQueen(board,row,column)){ | |
board[row][column] = true; | |
if(solve(board,column+1)) | |
return true; | |
board[row][column] = false; | |
} | |
printBoard(board); | |
} | |
return false; | |
} | |
public static void main(String[] args){ | |
boolean[][] board = new boolean[N][N]; | |
printBoard(board); | |
solve(board,0); | |
printBoard(board); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment