Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ENG/15/138
- ET
- */
- public class Queens {
- public static void main(String args[]) {
- int N = 8;
- int[][] chessboard = new int[N][N];
- solve(0, chessboard, N);
- for(int i = 0; i < N; i++) {
- for(int j = 0; j < N; j++) {
- if(chessboard[i][j]==1) System.out.print("Q ");
- else System.out.print("* ");
- }
- System.out.println();
- }
- }
- static boolean solve(int row, int[][] chessboard, int N) {
- if(row>=N) return true;
- for(int position = 0; position < N; position++) {
- if(isValid(chessboard, row, position, N)) {
- chessboard[row][position] = 1;
- if(!solve(row+1, chessboard, N)) {
- chessboard[row][position] = 0;
- } else
- return true;
- }
- }
- return false;
- }
- static boolean isValid(int[][] chessboard, int x, int y, int N) {
- int i, j;
- for(i = 0; i < x; i++)
- if(chessboard[i][y]==1)
- return false;
- i = x - 1;
- j = y - 1;
- while((i>=0)&&(j>=0))
- if(chessboard[i--][j--]==1) return false;
- i = x - 1;
- j = y + 1;
- while((i>=0)&&(j<N))
- if(chessboard[i--][j++]==1) return false;
- return true;
- }
- }
Add Comment
Please, Sign In to add comment