Optimize selection of next position.
Grid::next_pos was starting its scan from the position after the current one. This is inefficient as we know how large the square we've just placed is as we scan those positions. This optimisation just skips that square when starting the scan.
This commit is contained in:
10
main.cc
10
main.cc
@@ -140,14 +140,16 @@ struct Grid {
|
|||||||
return b - x(pos);
|
return b - x(pos);
|
||||||
}
|
}
|
||||||
|
|
||||||
auto next_pos(Pos const &pos) const noexcept -> Pos {
|
/** Get the next position to check. n is the size of the square we just
|
||||||
if (const auto p = x(pos) + 1 + y(pos) * length_; p >= grid_.size()) { return std::make_pair(0, length_); } else {
|
* added.
|
||||||
|
*/
|
||||||
|
auto next_pos(Pos const &pos, int n) const noexcept -> Pos {
|
||||||
|
const auto p = x(pos) + n + y(pos) * length_;
|
||||||
const auto next_p = grid_.find('.', p);
|
const auto next_p = grid_.find('.', p);
|
||||||
if (next_p == std::string::npos) {
|
if (next_p == std::string::npos) {
|
||||||
return std::make_pair(0, length_);
|
return std::make_pair(0, length_);
|
||||||
}
|
}
|
||||||
return std::make_pair(next_p % length_, next_p / length_);
|
return std::make_pair(next_p % length_, next_p / length_);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
std::string grid_;
|
std::string grid_;
|
||||||
@@ -176,7 +178,7 @@ auto find_solution_impl(Grid &grid, int n, Pos const &pos, Avail &avail_sqs) ->
|
|||||||
auto const sq = Square(pos, idx);
|
auto const sq = Square(pos, idx);
|
||||||
--avail_sqs[idx];
|
--avail_sqs[idx];
|
||||||
grid.add(sq);
|
grid.add(sq);
|
||||||
if (find_solution_impl(grid, n, grid.next_pos(pos), avail_sqs)) { return true; }
|
if (find_solution_impl(grid, n, grid.next_pos(pos, idx), avail_sqs)) { return true; }
|
||||||
++avail_sqs[idx];
|
++avail_sqs[idx];
|
||||||
grid.clear(sq);
|
grid.clear(sq);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user