I need to solve the N queens problem (place n queens on a chess board size nxn so that the queens don't attack each other). Consist of 4 class :
Queen.java : hold the row and column of the queen
Stack.java : a data structure stack to hold the queen.
Nqueens.java : to solve the problem
testN.java : to test the solution
the error I got is <identifier> expected in the testN.java, I don't really know what is going on, everything seems normal so far.
Here are the codes:
public class Queen{ int row; int column; public Queen(int r,int c){ row=r; column=c; } public int getRow(){ return row; } public int getCol(){ return column; } public boolean isConflict(Queen q) { boolean ans= false; //row and collum conflict if(row==q.row||column==q.column) ans=true; //same diagonal if the vector creats by two queens has same absolute value for x and y coordinator. else if(Math.abs(row-q.row)==Math.abs(column-q.column)) ans=true; return ans; } public String toString(){ String ans=""; ans=ans+"( "+row+" , "+column+" )"; return ans; } }
public class Stack { private Queen[] data; private int count; public Stack(int n){ data= new Queen[n]; } public void push(Queen item) { if(count==data.length) increaseSize(); data[count]=item; count++; } public int getSize(){ return count; } public Queen pop(){ Queen ans= null; if(count !=0)ans =data[count-1]; count--; return ans; } public Queen lookitem(int i){ Queen ans=null; if(count !=0)ans =data[i]; return ans; } public Queen peek() { Queen ans= null; if(count !=0)ans =data[count-1]; return ans; } public void increaseSize(){ Queen[] temp=new Queen[2*data.length+1]; for(int i=0;i<data.length;i++) { temp[i]=data[i]; } data=temp; } }
public class Nqueens{ private Stack s; private int N; public Nqueens(int size) { s=new Stack(size); N=size; } //Solve the nqueens problem public void solution() { s.push(new Queen(1,1));s.push(new Queen(2,1)); boolean solve=false; while(s.getSize()!=0&&solve==false) { boolean conflict=false;int i=0; while(i<s.getSize()-1&&conflict==false) { conflict=s.peek().isConflict(s.lookitem(i)); i++; } if (conflict=false) { while(s.getSize()!=0&&s.peek().getRow()==N) { s.pop(); } if(s.getSize()!=0) { Queen qq=new Queen(s.peek().getRow(),s.peek().getCol()+1); s.pop(); s.push(qq); } } else if(s.peek().getRow()==N) solve=true; else s.push(new Queen(s.peek().getRow()+1,1)); } } public String toString(){ String ans=""; for(int i=0;i<s.getSize();i++){ ans=ans+s.lookitem(i).toString()+" "; } return ans; }}
public class testN{ public static void main(String arg[]){ Queen q1=new Queen(1,1); Queen q2=new Queen(2,2); Queen q3=new Queen(2,1); Queen q4=new Queen(4,3); System.out.println(q1); System.out.println(q2); System.out.println(q1.isConflict(q4)); System.out.println(q4.isConflict(q3)); Stack s=new Stack(0); s.push(q1);s.push(q3); s.push(new Queen(3,6)); System.out.println("Element on s "+s.peek()); } Nqueens qq = new Nqueens(4); qq.solution(); System.out.println(qq); }