I dont seem to understand why java will not allow me to have the else if statement in the solve method under the while loop, it tells me it is a syntax error. I thought that with a condition after the else if statement it would be the correct syntax but it is not working for me.
//Class to solve simple N Queens problem with backtracking, but without using recursion in a 1-d array.
public class NQueens
{
private int N;
private int board[];
public NQueens(int n)
{
this.N = n;
this.board = new int[N];
for(int i = 0; i<N; i++)
{
this.board[i]=-1;
}
}
//checks the place for any attack queens in the same column, or diagnol
public boolean safePlace(int row, int col, int [] board)
{
for (int i = 0; i<row; i++)
{
if((board[i] == col)|| (i-row)==(board[i]-col)|| (i-row)==(col-board[i]))
return false;
}
return true;
}
//solves N Queens problem using backtracking
public void solve()
{
int row=0;
while(row<this.N && row>-1)
{ // condition that the row is empty and the queen is safe to place
int col=0;
if(this.board[row]==-1 && safePlace(row, col, this.board));
{
this.board[row]=col;
row++;
}
//condition that the row is not empty
else if(this.board[row]>-1)
{
//start at column after the previous queen's column position.
col=this.board[row-1]+1;
//checks for safety
if(safePlace(row, col, this.board))
{
this.board[row]=col;
}
}
else //condition that no safe column can be found so queen in row is removed and we move back one row
{
this.board[row]=-1;
row--;
}
}
printBoard();
}
public void printBoard()
{
System.out.println("got to solve loop");
for(int i = 0; i<N; i++)
{
int chessBoard[]=new int[N];
chessBoard[this.board[i]] = 1;
if(chessBoard[i]==0)
System.out.print("* ");
else
System.out.print("Q ");
}
}
public static void main(String[] args)
{
NQueens q = new NQueens(4);
q.solve();
}
}
Aucun commentaire:
Enregistrer un commentaire