My solution: DFS with backtracking
But I received Time Limit Exceeded
Here's the pseducode:
Code: Select all
class Position
{
std::set<T> setJumpPos_; // possible positions to which the Knight can go from the current position.
}
class Board
{
std::vector<Position<T> > vecPos_;
bool compute_path_recursive(T pos, std::vector<T>& path);
void compute_possible_moves();
}
/*
This is called for all the squares of the board. It populates setJumpPos_ for each of the position.
Its done in initialization stage.
*/
Code: Select all
/*
Here I do the DFS in a recursive manner.
*/
bool compute_path_recursive(T pos, std::vector<T>& path)
{
vecExplored_[pos] = true;
path.push_back(pos);
if (path.size() == nPos_)
{
return true;
}
bool path_found_flag = false;
std::set<T> jumpSet = vecPos_[pos].jumpPos();
// Trying out each of the next jump position from the current pos in a lexicographic manner.
for (std::set<T>::iterator it = jumpSet.begin(); it != jumpSet.end(); ++it)
{
if (!vecExplored_[(*it)])
{
if (compute_path_recursive((*it),path))
{
path_found_flag = true;
break;
}
}
}
if (!path_found_flag)
{
vecExplored_[pos] = false;
path.pop_back();
}
return path_found_flag;
}