I am trying to place the first queen on the board based on user input and then find a solution for the 7 remaining queens. The problem I'm having is the remaining queens are being placed as if the first doesn't exist. If I place a queen at row 3 column 0 for example remaining queens could be placed in the same row or column which shouldn't happen. Also 8 queens are being placed in addition to the first when it should be 7. Any help would be appreciated!
class Queen
{
// N x N chessboard
public static final int N = 8;
char board[][] = new char[N][N];
void printSolution(char board[][])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print(" " + board[i][j]
+ " ");
System.out.println();
}
}
// Function to check if two queens threaten each other or not
public boolean isSafe(char board[][], int row, int column)
{
// return false if two queens share the same column
for (int i = 0; i < row; i++)
if (board[i][column] == 'Q')
return false;
// return false if two queens share the same \ diagonal
for (int i = row, j = column; i >= 0 && j >= 0; i--, j--)
if (board[i][j] == 'Q')
return false;
// return false if two queens share the same / diagonal
for (int i = row, j = column; i >= 0 && j < N; i--, j++)
if (board[i][j] == 'Q')
return false;
return true;
}
public void nQueen(char board[][], int row)
{
// if N queens are placed successfully, print the solution
if (row == N)
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
System.out.print(board[i][j] + " ");
System.out.println();
}
System.out.println();
return;
}
// place Queen at every square in current row r
// and recurse for each valid movement
for (int i = 0; i < N; i++)
{
// if no two queens threaten each other
if (isSafe(board, row, i))
{
// place queen on current square
board[row][i] = 'Q';
// recurse for next row
nQueen(board, row + 1);
// backtrack and remove queen from current square
board[row][i] = '-';
}
}
}
public void setQueen(int row, int column)
{
board[row][column] = 'Q';
}
public static void main(String[] args)
{
// board[][] keeps track of position of Queens in
// the current configuration
Queen q = new Queen();
char[][] board = q.board;
System.out.println("Enter row: ");
int row = BIO.getInt();
System.out.println("Enter column ");
int col = BIO.getInt();
// initialize board[][] by '-'
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
board[i][j] = '-';
}
}
q.setQueen(row, col);
q.nQueen(board, 0);
}
}
Comments
Post a Comment