Last active
June 6, 2018 13:38
-
-
Save prameshbajra/50b309c73b7c063acc60103603b96941 to your computer and use it in GitHub Desktop.
NQueens - My solution
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
package com.demo.advjava; | |
public class NQueensTesting { | |
int boardSize = 8; | |
int[][] board = new int[boardSize][boardSize]; | |
public void populateBoard() { | |
int i, j; | |
for (i = 0; i < boardSize; i++) | |
for (j = 0; j < boardSize; j++) | |
board[i][j] = 0; | |
} | |
public void printBoard() { | |
int i, j; | |
for (i = 0; i < boardSize; i++) { | |
for (j = 0; j < boardSize; j++) | |
System.out.print(board[i][j] + " "); | |
System.out.println(); | |
} | |
} | |
public boolean placeQueen(int col) { | |
int i; | |
if (col >= boardSize) | |
return true; | |
for (i = 0; i < boardSize; i++) { | |
if (isSafe(i, col)) { | |
board[i][col] = 1; | |
if (placeQueen(col + 1)) | |
return true; | |
board[i][col] = 0; | |
} | |
} | |
return false; | |
} | |
private boolean isSafe(int row, int col) { | |
int i, j; | |
for (i = 0; i < col; i++) | |
if (board[row][i] == 1) | |
return false; | |
for (i = row, j = col; i >= 0 && j >= 0; i--, j--) | |
if (board[i][j] == 1) | |
return false; | |
for (i = row, j = col; j >= 0 && i < board.length; i++, j--) | |
if (board[i][j] == 1) | |
return false; | |
return true; | |
} | |
public static void main(String[] args) { | |
NQueensTesting nt = new NQueensTesting(); | |
nt.populateBoard(); | |
nt.placeQueen(0); | |
nt.printBoard(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment