Jan 7, 2009

How do you solve the 8-queens problem in chess? (The 8 queens have to be arranged in such a way that they do not mutually threaten each other? i.e. no

How do you solve the 8-queens problem in chess?
(The 8 queens have to be arranged in such a way that they do not mutually threaten each other? i.e. no two queens should share the same row/column or diagonal).
Use backtracking, check the board column by column, if the position is illegal, increment the row, if the position is illegal and is the last row of the column, backtracking,

Stack<pair(int,int)> s;
void Foo(int col, int board[8][8])
{
for(int i=0;i<8;i++)
{
if(!Attacked(col,i,board))//not attacked by previous queen
{
Update(col,i,board);
s.push(col,i);
if(col==7)
{
print s;
return;
}
Foo(col+1,board);
s.pop(col,i)
}
}
return;
}

No comments:

Post a Comment