There exits 2D array. We need to find out whether a given string ("microsoft") exits in the given matrix. The string can be vertical or horizontal or in snake form but not in diagonal.
mi..
...c.o..oft
.....r.s
the basic way is just scan the 2d array row by row (col by col ) and find the matching, we can use backtrack
{{{
int row;
int col;
int len;
char str[len]="microsoft";
char a[row][col]="…";
foo(int idx, int i,int j, char* str,const& char a[][col])
{
for(;i < row;i++,j=0)
for(;j < col;j++)
{
if(str[idx]==a[i][j])
{
if(idx==len-1) return true;
bool result=foo(idx+1,i,j+1,str,a);
if(result) return true;
}
}
return false;
}
}}}
Showing posts with label backtracking. Show all posts
Showing posts with label backtracking. Show all posts
Jul 31, 2009
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,
(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;
}
Subscribe to:
Posts (Atom)