Problem:
The 4-Queens Problem consists in placing four queens on a 4 x 4 chessboard so that no two queens can capture each other. That is, no two queens are allowed to be placed on the same row, the same column or the same diagonal.
// queen test class
package fourqueen;public class QueenTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Queen q=new Queen();
q.setQueen();
System.out.println("The Output is:");
q.showQueen();
}
}
//queen class
package fourqueen;public class Queen {
final public int n=4;
public int a[][]=new int [n][n];
//constructor for queen
public Queen(){
for (int i=0;i<n;i++){
for (int j=0;j<n;j++){
a[i][j]=0;
}
}
a[0][2]=1;//setting the initial queen
}
//function to check the position is right for queen or not
public boolean canPlaceQueen(int row,int col){
int i,j;
//checking left elements
for(i=0;i<col;i++){
if(a[row][i]==1){
return false;
}
}
//checking right elements
for( i=col;i<n;i++){
if(a[row][i]==1){
return false;
}
}
//checking upper element
for ( i=0;i<row;i++){
if(a[i][col]==1){
return false;
}
}
//checking lower element
for ( i=row;i<n;i++){
if(a[i][col]==1){
return false;
}
}
//checking left upper diagonal element
for( i=row, j=col;i>=0&&j>=0;i--,j--){
if(a[i][j]==1){
return false;
}
}
//checking right upper diagonal element
for( i=row, j=col;i>=0&&j<n;i--,j++){
if(a[i][j]==1){
return false;
}
}
//checking left lower diagonal element
for( i=row, j=col;i<n&&j>=0;i++,j--){
if(a[i][j]==1){
return false;
}
}
//checking right lower diagonal element
for( i=row, j=col;i<n&&j<n;i++,j++){
if(a[i][j]==1){
return false;
}
}
return true;
}
public void setQueen(){
int i,j;
//checking from second row as first queen is place in first row
for(i=1;i<n;i++){
for(j=0;j<n;j++){
if(canPlaceQueen(i,j)){
a[i][j]=1;
}
}
}
}
//function to print queen
public void showQueen(){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(a[i][j]==1){
System.out.print("Q ");
}
else
System.out.print(a[i][j]+" ");
}
System.out.println("");
}
}
}
Output:
The Output is:
0 0 Q 0
Q 0 0 0
0 0 0 Q
0 Q 0 0
No comments:
Post a Comment