Learnings

Thursday, October 04, 2007

N Queens problem

A crude version to solve the n-queens problem (wasn't as hard as I expected):

import java.lang.*;

class NQueens {
int N;
int[][] Board;
int soln=0;

public static void main(String[] args) {
int N=Integer.parseInt(args[0]);
NQueens nq = new NQueens(N);
System.out.println("Solving the "+N+"-queen problem.");
nq.search(0);

}

NQueens(int n) {
N=n;
Board = new int[N][N];
}

boolean IsValid() {
int tot=0;
int col=0;
int row=0;

// Check column totals first
for(col=0;col tot=0;
for(row=0;row tot+=Board[row][col];
if(tot>1)
return false;
}

// Check diagonals slanting right
for(col=0;col tot=0;
for(row=0;row<=col;row++) {
tot+=Board[row][col-row];
}
if(tot>1)
return false;
}

for(col=1;col tot=0;
for(row=N-1;row>=col;row--) {
tot+=Board[row][col+N-1-row];
}
if(tot>1)
return false;
}

//Check diagonals slanting left
for(col=N-1;col>=0;col--) {
tot=0;
for(row=0;row<=(N-1-col);row++) {
tot+=Board[row][col+row];
}
if(tot>1)
return false;
}

//Check diagonals slanting left
for(row=N-1;row>0;row--) {
tot=0;
for(col=0;col<=(N-1-row);col++) {
tot+=Board[row+col][col];
}
if(tot>1)
return false;
}
return true;

}

void search(int row) {
if (row==N) {
// We have found a solution!
soln++;
System.out.println("Solution "+soln);
printBoard();
return;
}

for(int col=0;col Board[row][col]=1;
if(IsValid()) {
search(row+1);
}
Board[row][col]=0;
}
}

void printBoard() {
for(int row=0;row for(int col=0;col if(Board[row][col]==1)
System.out.print(" Q ");
else
System.out.print(" X ");
}
System.out.println("");
}
}

}

0 Comments:

Post a Comment

<< Home