競技プログラミング用の C++ ライブラリ
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
#include "../../../src/graph/grid-graph.hpp"
#include <algorithm>
#include <cassert>
#include <cstdlib>
#include <iostream>
#include <limits>
#include <queue>
#include <random>
#include <set>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#if __cplusplus >= 202002L
#include <ranges>
#endif
#include "../../../src/graph/shortest-path.hpp"
using ll = long long;
using Cell = std::pair<ll, ll>;
static_assert(std::is_same_v<decltype(std::declval<const GridGraph&>().graph()), const Graph<ll>&>);
static_assert(std::is_same_v<decltype(std::declval<GridGraph&>().board()), const std::vector<std::string>&>);
static_assert(!std::is_assignable_v<decltype(std::declval<GridGraph&>().board()[0][0]), char>);
static_assert(!std::is_convertible_v<std::vector<std::string>, GridGraph>);
bool adjacent(Cell a, Cell b) {
return std::abs(a.first - b.first) + std::abs(a.second - b.second) == 1;
}
void verify(const GridGraph& maze, const std::vector<std::string>& board, char wall) {
const ll h = board.size(), w = board.empty() ? 0 : static_cast<ll>(board.front().size());
assert(maze.board() == board && maze.height() == h && maze.width() == w);
std::vector<Cell> cells;
for (ll i = 0; i < h; ++i) {
for (ll j = 0; j < w; ++j) {
const ll expected = board[i][j] == wall ? -1 : static_cast<ll>(cells.size());
assert(maze.index(i, j) == expected);
if (expected != -1) cells.emplace_back(i, j);
}
}
const ll n = cells.size();
assert(maze.size() == n && maze.graph().size() == n);
std::set<std::pair<ll, ll>> expected_edges, actual_edges;
for (ll u = 0; u < n; ++u) {
assert(maze.cell(u) == cells[u]);
assert(maze.label(u) == board[cells[u].first][cells[u].second]);
std::set<ll> expected_neighbors, actual_neighbors;
for (ll v = 0; v < n; ++v) {
if (adjacent(cells[u], cells[v])) {
expected_neighbors.insert(v);
if (u < v) expected_edges.emplace(u, v);
}
}
for (const auto& edge : maze[u]) {
assert(edge.src == u && edge.cost == 1 && 0 <= edge.dst && edge.dst < n);
actual_neighbors.insert(edge.dst);
}
assert(actual_neighbors == expected_neighbors && maze[u].size() == expected_neighbors.size());
assert(&maze[u] == &maze.graph()[u]);
}
assert(maze.graph().edge_count() == static_cast<ll>(expected_edges.size()));
std::vector<ll> edge_occurrences(maze.graph().edge_count());
for (ll u = 0; u < n; ++u) {
for (const auto& edge : maze[u]) {
assert(0 <= edge.id && edge.id < maze.graph().edge_count());
++edge_occurrences[edge.id];
}
}
for (ll count : edge_occurrences) assert(count == 2);
for (const auto& edge : maze.graph().edges()) actual_edges.emplace(std::min(edge.src, edge.dst), std::max(edge.src, edge.dst));
assert(actual_edges == expected_edges);
for (char c : {'S', 'G', '.', '#', 'a', 'X', '\0'}) {
std::vector<ll> expected;
for (ll v = 0; v < n; ++v) {
if (board[cells[v].first][cells[v].second] == c) expected.push_back(v);
}
const auto matches = maze.find_all(c);
assert(std::vector<ll>(matches.begin(), matches.end()) == expected);
assert(std::vector<ll>(matches.begin(), matches.end()) == expected);
assert(maze.find(c) == (expected.empty() ? -1 : expected.front()));
// 一時的な検索rangeがなくなっても、iteratorの走査状態は独立している。
auto it = maze.find_all(c).begin();
for (ll v : expected) {
auto independent = it;
decltype(it) assigned;
assigned = it;
assert(*it++ == v && *independent == v && *assigned == v);
++independent;
assert(independent == it);
}
assert(it == matches.end());
#if __cplusplus >= 202002L
static_assert(std::ranges::forward_range<decltype(matches)>);
auto selected = maze.find_all(c) | std::views::take(1);
std::vector<ll> first;
std::ranges::copy(selected, std::back_inserter(first));
assert(first == (expected.empty() ? std::vector<ll>{} : std::vector<ll>{expected.front()}));
#endif
}
// Gridを使わず、座標のマンハッタン距離だけで隣接を判定するBFSと比較する。
const ll inf = std::numeric_limits<ll>::max() / 4;
for (ll s = 0; s < n; ++s) {
std::vector<ll> expected(n, inf);
std::queue<ll> queue;
expected[s] = 0;
queue.push(s);
while (!queue.empty()) {
const ll u = queue.front();
queue.pop();
for (ll v = 0; v < n; ++v) {
if (expected[v] != inf || !adjacent(cells[u], cells[v])) continue;
expected[v] = expected[u] + 1;
queue.push(v);
}
}
const auto result = shortest_path_bfs(maze.graph(), s);
assert(result.dist == expected);
for (ll t = 0; t < n; ++t) {
const auto path = result.path(t);
assert(path.has_value() == (expected[t] != inf));
if (path) {
assert(path->vertices.front() == s && path->vertices.back() == t);
assert(path->cost == expected[t] && static_cast<ll>(path->edges.size()) == expected[t]);
for (ll i = 1; i < static_cast<ll>(path->vertices.size()); ++i) {
assert(adjacent(maze.cell(path->vertices[i - 1]), maze.cell(path->vertices[i])));
}
}
}
}
}
int main() {
for (const auto& board : std::vector<std::vector<std::string>>{
{}, {"", ""}, {"#"}, {"."}, {"S"}, {"###", "###"}, {"S#G"}, {"S", "#", "G"}, {"S..#.", ".#...", "...G."}, {"aaa", "a#a", "aaa"}}) {
verify(GridGraph(board), board, '#');
}
verify(GridGraph({"S#XG", "aX.a"}, 'X'), {"S#XG", "aX.a"}, 'X');
verify(GridGraph({"S.G"}, 'S'), {"S.G"}, 'S');
const std::vector<std::string> binary = {std::string("a\0#", 3)};
verify(GridGraph(binary), binary, '#');
{
const std::vector<std::string> expected = {"S..#.", ".#...", "...G."};
auto input = expected;
GridGraph maze(input);
input.clear();
verify(maze, expected, '#');
const GridGraph copy(maze);
verify(copy, expected, '#');
GridGraph moved(std::move(maze));
verify(moved, expected, '#');
assert(shortest_path_bfs(moved.graph(), moved.find('S')).dist[moved.find('G')] == 5);
}
std::mt19937 rng(314);
for (int rep = 0; rep < 600; ++rep) {
const ll h = rng() % 8, w = rng() % 8;
std::vector<std::string> board(h, std::string(w, '.'));
for (auto& row : board) {
for (char& c : row) c = std::string("##..aSGX")[rng() % 8];
}
const char wall = rep % 2 == 0 ? '#' : 'X';
verify(GridGraph(board, wall), board, wall);
}
std::cout << "Hello World\n";
}#line 1 "test/unittest/graph/grid-graph.test.cpp"
#define PROBLEM "https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ITP1_1_A"
#line 2 "src/graph/grid-graph.hpp"
/**
* @file grid-graph.hpp
* @brief 文字列盤面から作るグリッドグラフ
*/
#include <cassert>
#include <cstddef>
#include <iterator>
#include <string>
#include <utility>
#include <vector>
#line 2 "src/utility/range.hpp"
/**
* @file range.hpp
* @brief Python の range のような整数列と、その直積の Grid
*/
#line 12 "src/utility/range.hpp"
#include <type_traits>
#line 15 "src/utility/range.hpp"
struct Range {
public:
using value_type = long long;
using const_reference = value_type;
using size_type = long long;
using difference_type = std::ptrdiff_t;
const value_type start;
const value_type stop;
const value_type step;
private:
const value_type norm_stop;
constexpr static value_type normalize(value_type _start, value_type _stop, value_type _step) {
assert(_step != 0);
if (_step > 0) {
if (_start >= _stop) {
return _start;
} else {
return _start + (_stop - _start + _step - 1) / _step * _step;
}
} else {
if (_start <= _stop) {
return _start;
} else {
return _start - (_start - _stop - _step - 1) / _step * _step;
}
}
}
constexpr Range(value_type _start, value_type _stop, value_type _step, value_type _norm_stop)
: start(_start), stop(_stop), step(_step), norm_stop(_norm_stop) {
}
public:
/**
* @brief start から stop の手前まで step ずつ進む整数列
* @pre step != 0
*/
constexpr Range(value_type _start, value_type _stop, value_type _step)
: start(_start), stop(_stop), step(_step), norm_stop(normalize(_start, _stop, _step)) {
}
constexpr Range(value_type _start, value_type _stop)
: start(_start), stop(_stop), step(1), norm_stop(normalize(_start, _stop, 1)) {}
explicit constexpr Range(value_type _stop)
: start(0), stop(_stop), step(1), norm_stop(normalize(0, _stop, 1)) {}
constexpr Range()
: start(0), stop(0), step(1), norm_stop(0) {
}
constexpr Range(const Range& o) = default;
Range& operator=(const Range& o) = delete;
struct const_iterator {
public:
using difference_type = Range::difference_type;
using value_type = Range::value_type;
using pointer = void;
using reference = Range::const_reference;
using iterator_category = std::random_access_iterator_tag;
private:
value_type first = 0, stop = 0, step = 1, value = 0;
constexpr bool same_range(const const_iterator& o) const noexcept {
return first == o.first && stop == o.stop && step == o.step;
}
public:
constexpr const_iterator() noexcept = default;
constexpr const_iterator(const Range& range, value_type value) noexcept
: first(range.start), stop(range.stop), step(range.step), value(value) {}
constexpr reference base() const noexcept {
return value;
}
constexpr const_iterator& operator++() noexcept {
value += step;
return *this;
}
constexpr const_iterator operator++(int) noexcept {
const_iterator ret(*this);
value += step;
return ret;
}
constexpr const_iterator& operator+=(difference_type _n) noexcept {
value += _n * step;
return *this;
}
constexpr friend const_iterator operator+(const const_iterator& i, difference_type _n) noexcept {
const_iterator ret(i);
ret += _n;
return ret;
}
constexpr friend const_iterator operator+(difference_type _n, const const_iterator& i) noexcept {
const_iterator ret(i);
ret += _n;
return ret;
}
constexpr const_iterator& operator--() noexcept {
value -= step;
return *this;
}
constexpr const_iterator operator--(int) noexcept {
const_iterator ret(*this);
value -= step;
return ret;
}
constexpr const_iterator& operator-=(difference_type _n) noexcept {
value -= _n * step;
return *this;
}
constexpr friend const_iterator operator-(const const_iterator& i, difference_type _n) noexcept {
const_iterator ret(i);
ret -= _n;
return ret;
}
constexpr reference operator[](difference_type i) const noexcept { return value + i * step; }
constexpr reference operator*() const noexcept {
return value;
}
constexpr friend bool operator!=(const const_iterator& a, const const_iterator& b) noexcept {
return !a.same_range(b) || a.value != b.value;
}
constexpr friend bool operator==(const const_iterator& a, const const_iterator& b) noexcept {
return !(a != b);
}
constexpr friend bool operator<(const const_iterator& a, const const_iterator& b) noexcept {
assert(a.same_range(b));
return a.step > 0 ? a.value < b.value : a.value > b.value;
}
constexpr friend bool operator>(const const_iterator& a, const const_iterator& b) noexcept { return b < a; }
constexpr friend bool operator<=(const const_iterator& a, const const_iterator& b) noexcept { return !(b < a); }
constexpr friend bool operator>=(const const_iterator& a, const const_iterator& b) noexcept { return !(a < b); }
constexpr friend difference_type operator-(const const_iterator& a, const const_iterator& b) {
assert(a.same_range(b));
if (a.step > 0) {
return (a.value - b.value) / a.step;
} else {
return (b.value - a.value) / (-a.step);
}
}
};
constexpr const_iterator begin() const noexcept {
return {*this, start};
}
constexpr const_iterator end() const noexcept {
return {*this, norm_stop};
}
/**
* @brief x の個数 (0 か 1)
*/
constexpr size_type count(value_type x) const noexcept {
// step がコンパイル時に分からないときも、よく使う step = 1 では割り算をしない
if (step == 1) return start <= x && x < stop;
if (step > 0) {
if (start <= x && x < stop) {
if ((x - start) % step == 0) {
return 1;
}
}
} else {
if (stop < x && x <= start) {
if ((start - x) % (-step) == 0) {
return 1;
}
}
}
return 0;
}
/**
* @brief x が含まれるか
*/
constexpr bool contains(value_type x) const noexcept {
return count(x) != 0;
}
/**
* @brief x のインデックス
* x が含まれないとエラー
*/
constexpr size_type index(value_type x) const {
assert(contains(x));
if (step == 1) return x - start;
return (x - start) / step;
}
/**
* @brief 要素が x のイテレータ
* x が含まれないと end() を返す
*/
constexpr const_iterator find(value_type x) const noexcept {
if (contains(x)) {
return {*this, x};
} else {
return {*this, norm_stop};
}
}
/**
* @brief 要素が x 以上の最小のイテレータ
* step > 0 じゃないとエラー
*/
constexpr const_iterator lower_bound(value_type x) const {
assert(step > 0);
if (norm_stop <= x) {
return end();
} else if (x < start) {
return begin();
} else {
return {*this, start + (x - start + step - 1) / step * step};
}
}
/**
* @brief 要素が x より大きい最小のイテレータ
* step > 0 じゃないとエラー
*/
constexpr const_iterator upper_bound(value_type x) const {
assert(step > 0);
if (norm_stop <= x) {
return end();
} else if (x < start) {
return begin();
} else {
return {*this, start + (x - start + step) / step * step};
}
}
/**
* @brief コンテナの要素数
*/
constexpr size_type size() const noexcept {
if (step > 0) {
return (norm_stop - start) / step;
} else {
return (start - norm_stop) / (-step);
}
}
constexpr value_type at(size_type i) const {
assert(0 <= i && i < size());
return start + i * step;
}
constexpr value_type operator[](size_type i) const {
return at(i);
}
constexpr bool empty() const noexcept {
return start == norm_stop;
}
constexpr value_type sum() const noexcept {
return size() * (norm_stop - step + start) / 2;
}
/**
* @brief 最小値
* 空だとエラー
*/
constexpr value_type min() const {
assert(!empty());
if (step > 0) {
return start;
} else {
return norm_stop - step;
}
}
/**
* @brief 最大値
* 空だとエラー
*/
constexpr value_type max() const {
assert(!empty());
if (step > 0) {
return norm_stop - step;
} else {
return start;
}
}
/**
* @brief 総 xor
* 負を含むとエラー
*/
constexpr value_type product_xor() const noexcept {
if (empty()) return 0;
assert(min() >= 0);
Range sorted_range(sorted());
value_type res = 0;
std::make_unsigned_t<value_type> t = 1;
while (t <= static_cast<std::make_unsigned_t<value_type>>(max())) {
std::make_unsigned_t<value_type> tmp = 0, n = size(), m = t, a = sorted_range.step, b = sorted_range.start;
while (true) {
if (a >= m) {
tmp += n * (n - 1) / 2 * (a / m);
a %= m;
}
if (b >= m) {
tmp += n * (b / m);
b %= m;
}
std::make_unsigned_t<value_type> y_max = a * n + b;
if (y_max < m) break;
n = y_max / m;
b = y_max % m;
std::swap(m, a);
}
if (tmp % 2 == 1) {
res += t;
}
t <<= 1;
}
return res;
}
/**
* @brief 逆順にしたもの
*/
constexpr Range reversed() const noexcept {
return {norm_stop - step, start - step, -step, start - step};
}
/**
* @brief step > 0 だとそのまま step < 0 だと逆順にしたもの
*/
constexpr Range sorted() const noexcept {
if (step > 0) {
return {start, norm_stop, step, norm_stop};
} else {
return {norm_stop - step, start - step, -step, start - step};
}
}
/**
* @brief 要素が [l, r) である範囲を返す
*/
constexpr Range clipped(value_type l, value_type r) const {
if (l >= r) return {};
r--; // 以下では r を含む [l, r] として扱う
if (step > 0) {
value_type _start = [&] {
if (norm_stop <= l) {
return norm_stop;
} else if (l < start) {
return start;
} else {
return start + (l - start + step - 1) / step * step;
}
}();
value_type _stop = [&] {
if (norm_stop <= r) {
return norm_stop;
} else if (r < start) {
return start;
} else {
return start + (r - start + step) / step * step;
}
}();
return {_start, _stop, step, _stop};
} else {
value_type _start = [&] {
if (start - step <= r) {
return start;
} else if (r < norm_stop - step) {
return norm_stop;
} else {
return norm_stop + (r - norm_stop) / step * step;
}
}();
value_type _stop = [&] {
if (start - step <= l) {
return start;
} else if (l < norm_stop - step) {
return norm_stop;
} else {
return norm_stop + (l - norm_stop - 1) / step * step;
}
}();
return {_start, _stop, step, _stop};
}
}
/**
* @brief 要素を Range で指定したコンテナ
*/
constexpr Range slice(const Range& r) const {
if (r.empty()) return {};
if (r.max() < 0) return {};
if (r.min() >= size()) return {};
Range trimmed_range(r.clipped(0, size()));
if (trimmed_range.empty()) return {};
value_type _step = step * trimmed_range.step;
value_type _start = at(trimmed_range.start);
value_type _stop = _start + _step * trimmed_range.size();
return {_start, _stop, _step, _stop};
}
static std::string type_str() {
return "Range";
}
std::string initializer_str() const {
return "{" + std::to_string(start) + ", " + std::to_string(stop) + ", " + std::to_string(step) + "}";
}
std::string repr() const {
return "Range(" + std::to_string(start) + ", " + std::to_string(stop) + ", " + std::to_string(step) + ")";
}
std::vector<value_type> to_vector() const {
std::vector<value_type> ret;
ret.reserve(size());
if (step > 0) {
for (value_type x = start; x < stop; x += step) {
ret.push_back(x);
}
} else {
for (value_type x = start; x > stop; x += step) {
ret.push_back(x);
}
}
return ret;
}
constexpr friend bool operator==(const Range& a, const Range& b) noexcept {
if (a.empty() && b.empty()) return true;
if (a.size() != b.size()) return false;
if (a.start != b.start) return false;
if (a.size() == 1) return true;
if (a.step != b.step) return false;
return true;
}
constexpr friend bool operator!=(const Range& a, const Range& b) noexcept {
return !(a == b);
}
};
/**
* @brief 2 つの Range の直積 rows × cols
* (i, j) を i の昇順、同じ i では j の昇順 (行優先) に並べたものとして扱う
*/
struct Grid {
public:
using value_type = std::pair<long long, long long>;
using size_type = long long;
using difference_type = std::ptrdiff_t;
const Range rows;
const Range cols;
private:
const long long width; // cols.size() (index や at で毎回割り算しないように持っておく)
public:
/**
* @brief [0, h) × [0, w)
*/
constexpr Grid(long long h, long long w) : rows(h), cols(w), width(cols.size()) {}
constexpr Grid(const Range& _rows, const Range& _cols) : rows(_rows), cols(_cols), width(cols.size()) {}
constexpr Grid(const Grid& o) = default;
Grid& operator=(const Grid& o) = delete;
struct const_iterator {
public:
using difference_type = Grid::difference_type;
using value_type = Grid::value_type;
using pointer = void;
using reference = value_type;
using iterator_category = std::forward_iterator_tag;
private:
const Grid* rect = nullptr;
long long w = 0; // cols.size()
long long ic = 0; // rows の何番目か
long long jc = 0; // cols の何番目か
public:
constexpr const_iterator() noexcept = default;
constexpr const_iterator(const Grid* _rect, long long _w, long long _ic, long long _jc) noexcept
: rect(_rect), w(_w), ic(_ic), jc(_jc) {}
constexpr value_type operator*() const noexcept {
return {rect->rows.start + ic * rect->rows.step, rect->cols.start + jc * rect->cols.step};
}
constexpr const_iterator& operator++() noexcept {
if (++jc == w) {
jc = 0;
++ic;
}
return *this;
}
constexpr const_iterator operator++(int) noexcept {
const_iterator ret(*this);
++*this;
return ret;
}
constexpr friend bool operator==(const const_iterator& a, const const_iterator& b) noexcept {
return a.ic == b.ic && a.jc == b.jc;
}
constexpr friend bool operator!=(const const_iterator& a, const const_iterator& b) noexcept {
return !(a == b);
}
};
constexpr const_iterator begin() const noexcept {
return {this, width, width == 0 ? rows.size() : 0, 0};
}
constexpr const_iterator end() const noexcept {
return {this, width, rows.size(), 0};
}
/**
* @brief 要素数 rows.size() * cols.size()
*/
constexpr size_type size() const noexcept {
return rows.size() * width;
}
constexpr bool empty() const noexcept {
return rows.empty() || cols.empty();
}
/**
* @brief (i, j) が含まれるか
*/
constexpr bool contains(long long i, long long j) const noexcept {
return rows.contains(i) && cols.contains(j);
}
constexpr bool contains(const value_type& p) const noexcept {
return contains(p.first, p.second);
}
/**
* @brief (i, j) の行優先での位置 (グリッドの頂点番号に使う)
* (i, j) が含まれないとエラー
*/
constexpr size_type index(long long i, long long j) const {
assert(contains(i, j));
return rows.index(i) * width + cols.index(j);
}
constexpr size_type index(const value_type& p) const {
return index(p.first, p.second);
}
/**
* @brief 行優先で k 番目の要素 (index の逆)
*/
constexpr value_type at(size_type k) const {
assert(0 <= k && k < size());
return {rows[k / width], cols[k % width]};
}
constexpr value_type operator[](size_type k) const {
return at(k);
}
private:
// 近傍の方向 (rows・cols の中での位置の差) を Grid の順に並べたもの。先頭 4 つは上下左右だけを並べた別の表
// 4 近傍と 8 近傍の境目が分かるように 2 行に分けているので整形しない
// clang-format off
static constexpr int neighbor_dirs[12][2] = {{-1, 0}, {0, -1}, {0, 1}, {1, 0},
{-1, -1}, {-1, 0}, {-1, 1}, {0, -1}, {0, 1}, {1, -1}, {1, 0}, {1, 1}};
// clang-format on
public:
/**
* @brief neighbors4 / neighbors8 の戻り値 (範囲 for で使う)
* 作るときに Grid に含まれる方向をビットで持っておき、立っているビットを順に返す
*/
struct Neighbors {
long long i, j, row_step, col_step;
int first; // neighbor_dirs[first + k] がビット k の方向
unsigned mask; // Grid に含まれる方向
struct iterator {
using difference_type = std::ptrdiff_t;
using value_type = Grid::value_type;
using pointer = void;
using reference = value_type;
using iterator_category = std::forward_iterator_tag;
const Neighbors* nb = nullptr;
unsigned rest = 0; // まだ返していない方向
constexpr value_type operator*() const noexcept {
const int k = nb->first + __builtin_ctz(rest);
return {nb->i + neighbor_dirs[k][0] * nb->row_step, nb->j + neighbor_dirs[k][1] * nb->col_step};
}
constexpr iterator& operator++() noexcept {
rest &= rest - 1;
return *this;
}
constexpr iterator operator++(int) noexcept {
iterator ret(*this);
++*this;
return ret;
}
constexpr friend bool operator==(const iterator& a, const iterator& b) noexcept { return a.rest == b.rest; }
constexpr friend bool operator!=(const iterator& a, const iterator& b) noexcept { return a.rest != b.rest; }
};
constexpr iterator begin() const noexcept { return {this, mask}; }
constexpr iterator end() const noexcept { return {this, 0}; }
constexpr long long size() const noexcept { return __builtin_popcount(mask); }
constexpr bool empty() const noexcept { return mask == 0; }
};
private:
constexpr Neighbors neighbors(long long i, long long j, int first, int last) const {
assert(contains(i, j));
unsigned mask = 0;
for (int k = first; k < last; k++) {
if (contains(i + neighbor_dirs[k][0] * rows.step, j + neighbor_dirs[k][1] * cols.step)) mask |= 1u << (k - first);
}
return {i, j, rows.step, cols.step, first, mask};
}
public:
/**
* @brief (i, j) の上下左右のうち Grid に含まれるものを、Grid の順に返す
* 隣は rows・cols の中で隣り合う要素 (i ± rows.step など)。(i, j) が含まれないとエラー
*/
constexpr Neighbors neighbors4(long long i, long long j) const {
return neighbors(i, j, 0, 4);
}
constexpr Neighbors neighbors4(const value_type& p) const {
return neighbors4(p.first, p.second);
}
/**
* @brief (i, j) を囲む 8 つのうち Grid に含まれるものを、Grid の順に返す
*/
constexpr Neighbors neighbors8(long long i, long long j) const {
return neighbors(i, j, 4, 12);
}
constexpr Neighbors neighbors8(const value_type& p) const {
return neighbors8(p.first, p.second);
}
static std::string type_str() {
return "Grid";
}
std::string initializer_str() const {
return "{" + rows.initializer_str() + ", " + cols.initializer_str() + "}";
}
std::string repr() const {
return "Grid(" + rows.repr() + ", " + cols.repr() + ")";
}
constexpr friend bool operator==(const Grid& a, const Grid& b) noexcept {
if (a.empty() && b.empty()) return true;
return a.rows == b.rows && a.cols == b.cols;
}
constexpr friend bool operator!=(const Grid& a, const Grid& b) noexcept {
return !(a == b);
}
};
#line 2 "src/graph/graph.hpp"
/**
* @file graph.hpp
* @brief グラフ
*/
#line 9 "src/graph/graph.hpp"
#include <iostream>
#line 12 "src/graph/graph.hpp"
/**
* @brief グラフの汎用クラス
*
* @tparam Cost 辺のコストの型 省略したら long long (重みの和や未到達を表す max / 4 があふれにくいように)
*/
template <typename Cost = long long>
class Graph {
public:
/**
* @brief 有向辺の構造体
*
* operator long long()を定義しているので、整数型にキャストすると勝手にdstになる
* 例えば、
* for (auto& e : g[v]) をすると、vから出る辺が列挙されるが、
* for (long long dst : g[v]) とすると、vから出る辺の行き先が列挙される
*/
struct Edge {
long long src = -1; //!< 始点
long long dst = -1; //!< 終点
Cost cost = {}; //!< コスト
long long id = -1; //!< 辺の番号(追加された順、無向辺の場合はidが同じで方向が逆のものが2つ存在する)
Edge() = default;
Edge(long long src, long long dst, Cost cost = 1, long long id = -1) : src(src), dst(dst), cost(cost), id(id) {}
operator long long() const { return dst; }
};
private:
long long n; //!< 頂点数
long long m; //!< 辺数
std::vector<std::vector<Edge>> g; //!< グラフの隣接リスト表現
public:
/**
* @brief デフォルトコンストラクタ
*/
Graph() : n(0), m(0), g(0) {}
/**
* @brief コンストラクタ
* @param n 頂点数
*/
explicit Graph(long long n) : n(n), m(0), g(n) {}
/**
* @brief 頂点数
*/
long long size() const { return n; }
/**
* @brief 辺数 (無向辺は 1 本と数える)
*/
long long edge_count() const { return m; }
/**
* @brief 無向辺を追加する
* @param u 始点
* @param v 終点
* @param w コスト 省略したら1
*/
void add_edge(long long u, long long v, Cost w = 1) {
assert(0 <= u && u < n && 0 <= v && v < n);
g[u].push_back({u, v, w, m});
g[v].push_back({v, u, w, m++});
}
/**
* @brief 有向辺を追加する
* @param u 始点
* @param v 終点
* @param w コスト 省略したら1
*/
void add_directed_edge(long long u, long long v, Cost w = 1) {
assert(0 <= u && u < n && 0 <= v && v < n);
g[u].push_back({u, v, w, m++});
}
/**
* @brief 辺の情報を標準入力から受け取って追加する
* @param m 辺の数
* @param padding 頂点番号を入力からいくつずらすか 省略したら-1
* @param weighted 辺の重みが入力されるか 省略したらfalseとなり、重み1で辺が追加される
* @param directed 有向グラフかどうか 省略したらfalse
*/
void read(long long m, long long padding = -1, bool weighted = false, bool directed = false) {
for (long long i = 0; i < m; i++) {
long long u, v;
std::cin >> u >> v;
u += padding, v += padding;
Cost c(1);
if (weighted)
std::cin >> c;
if (directed)
add_directed_edge(u, v, c);
else
add_edge(u, v, c);
}
}
/**
* @brief ある頂点から出る辺を列挙する
* @param v 頂点番号
* @return const std::vector<Edge>& vから出る辺のリスト
*/
const std::vector<Edge>& operator[](long long v) const {
assert(0 <= v && v < n);
return g[v];
}
/**
* @brief 辺のリスト
* @return std::vector<Edge> 辺のリスト(idの昇順)
*
* 無向辺は代表して1つだけ格納される。その src と dst の向きは規定しない
* 有向辺は追加したときの向きのまま格納される
*/
std::vector<Edge> edges() const {
std::vector<Edge> res(m);
for (long long i = 0; i < n; i++) {
for (auto& e : g[i]) {
res[e.id] = e;
}
}
return res;
}
};
/**
* @brief 経路 (路・閉路)。長さ cost、たどる頂点の列 vertices、たどる辺の列 edges
*
* edges[k] は vertices[k] から vertices[k + 1] へ向かう (edges[k].src == vertices[k]、edges[k].dst == vertices[k + 1])
* vertices は edges より 1 つ多い。辺がなくても始点 1 つが入る。閉路なら vertices.front() == vertices.back()
* auto [cost, vertices, edges] = *shortest_path(g, s, t); のように受け取れる
*/
template <typename Cost>
struct Path {
Cost cost; //!< 長さ (辺のコストの和)
std::vector<long long> vertices; //!< たどる頂点 (始点から順に)
std::vector<typename Graph<Cost>::Edge> edges; //!< たどる辺 (始点側から順に)
};
namespace internal_graph {
/**
* @brief 始点 s と、s からたどる順に並べた辺 edges から Path を作る。cost は辺のコストの和
*/
template <typename Cost>
Path<Cost> make_path(long long s, std::vector<typename Graph<Cost>::Edge> edges) {
Path<Cost> res{Cost{}, {s}, std::move(edges)};
for (const auto& e : res.edges) {
assert(e.src == res.vertices.back());
res.cost += e.cost;
res.vertices.push_back(e.dst);
}
return res;
}
} // namespace internal_graph
#line 17 "src/graph/grid-graph.hpp"
/**
* @brief 壁以外のマスを頂点とする、4 近傍・重み 1 の無向グラフ
* 元の盤面と座標対応を保持する。頂点番号は通行可能なマスに行優先で付ける。
*/
class GridGraph {
std::vector<std::string> data;
long long h, w;
std::vector<long long> ids;
std::vector<Grid::value_type> cells;
Graph<long long> g;
class Matches {
const GridGraph* owner;
char c;
public:
Matches(const GridGraph* owner, char c) : owner(owner), c(c) {}
class iterator {
const GridGraph* owner = nullptr;
char c = 0;
long long v = -1;
void seek() {
while (v < owner->size() && owner->label(v) != c) ++v;
if (v == owner->size()) v = -1;
}
public:
using value_type = long long;
using difference_type = std::ptrdiff_t;
using reference = value_type;
using pointer = void;
using iterator_category = std::input_iterator_tag;
using iterator_concept = std::forward_iterator_tag;
iterator() = default;
iterator(const GridGraph* owner, char c) : owner(owner), c(c), v(0) { seek(); }
value_type operator*() const { return v; }
iterator& operator++() {
++v;
seek();
return *this;
}
iterator operator++(int) {
auto previous = *this;
++*this;
return previous;
}
bool operator==(const iterator& other) const {
if (v == -1 || other.v == -1) return v == other.v;
return owner == other.owner && c == other.c && v == other.v;
}
bool operator!=(const iterator& other) const { return !(*this == other); }
};
iterator begin() const { return iterator(owner, c); }
iterator end() const { return iterator(); }
};
public:
/**
* @brief 盤面を所有し、壁以外のマスからグラフを構築する O(HW)
* @pre 各行の長さが等しいこと。空の盤面や幅 0 の盤面もよい。
*/
explicit GridGraph(std::vector<std::string> board, char wall = '#')
: data(std::move(board)), h(static_cast<long long>(data.size())), w(data.empty() ? 0 : static_cast<long long>(data.front().size())) {
for (const auto& row : data) assert(static_cast<long long>(row.size()) == w);
const Grid grid(h, w);
ids.assign(grid.size(), -1);
for (auto [i, j] : grid) {
if (data[i][j] == wall) continue;
ids[grid.index(i, j)] = size();
cells.emplace_back(i, j);
}
g = Graph<long long>(size());
for (long long u = 0; u < size(); ++u) {
const auto [i, j] = cell(u);
for (auto [ni, nj] : grid.neighbors4(i, j)) {
const long long v = index(ni, nj);
// 壁 (-1) を除き、各無向辺を 1 回だけ追加する。
if (u < v) g.add_edge(u, v);
}
}
}
const Graph<long long>& graph() const { return g; }
long long size() const { return static_cast<long long>(cells.size()); }
long long height() const { return h; }
long long width() const { return w; }
const std::vector<Graph<long long>::Edge>& operator[](long long v) const { return g[v]; }
const std::vector<std::string>& board() const { return data; }
/** @brief 座標に対応する頂点番号。壁なら -1、範囲外なら assert */
long long index(long long i, long long j) const { return ids[Grid(h, w).index(i, j)]; }
/** @brief 頂点番号に対応する座標 */
Grid::value_type cell(long long v) const {
assert(0 <= v && v < size());
return cells[v];
}
/** @brief 頂点に対応する文字 */
char label(long long v) const {
const auto [i, j] = cell(v);
return data[i][j];
}
/** @brief 文字 c に対応する最初の頂点番号。なければ -1。O(V) */
long long find(char c) const {
const auto matches = find_all(c);
const auto it = matches.begin();
return it == matches.end() ? -1 : *it;
}
/**
* @brief 文字 c に対応する頂点番号を行優先で遅延列挙する。構築 O(1)、全走査 O(V)
* @pre 走査中は元の GridGraph を有効なまま保持し、変更しないこと。
*/
Matches find_all(char c) const { return Matches(this, c); }
};
#line 4 "test/unittest/graph/grid-graph.test.cpp"
#include <algorithm>
#line 7 "test/unittest/graph/grid-graph.test.cpp"
#include <cstdlib>
#line 9 "test/unittest/graph/grid-graph.test.cpp"
#include <limits>
#include <queue>
#include <random>
#include <set>
#line 17 "test/unittest/graph/grid-graph.test.cpp"
#if __cplusplus >= 202002L
#include <ranges>
#endif
#line 2 "src/graph/shortest-path.hpp"
/**
* @file shortest-path.hpp
* @brief 最短路
*/
#line 10 "src/graph/shortest-path.hpp"
#include <deque>
#include <functional>
#line 13 "src/graph/shortest-path.hpp"
#include <optional>
#line 17 "src/graph/shortest-path.hpp"
#line 19 "src/graph/shortest-path.hpp"
/**
* @brief 1 点から全点への最短路の結果
*
* auto [dist, prev] = shortest_path_dijkstra(g, s); のように受け取れる
*/
template <typename Cost>
struct ShortestPath {
using Edge = typename Graph<Cost>::Edge;
std::vector<Cost> dist; //!< 各頂点への最短路長
std::vector<Edge> prev; //!< 各頂点への最短路上の直前の辺 (始点と未到達の頂点では src == -1)
/**
* @brief 始点から t への最短路 (長さ、たどる頂点、たどる辺)
* cost は dist[t] (shortest_path_bfs では辺の本数)
* @return std::optional<Path<Cost>> t が始点なら長さ 0、頂点は t だけ、辺は空。未到達なら std::nullopt
* @note 負閉路の影響を受ける頂点では最短路が定まらない (assert で落ちる)
*/
std::optional<Path<Cost>> path(long long t) const {
// 直前の辺がないのは始点と未到達の頂点。始点の距離は 0 で、未到達の距離 inf は正なので区別できる
if (prev[t].src == -1 && dist[t] != Cost{}) return std::nullopt;
Path<Cost> res{dist[t], {t}, {}};
while (prev[t].src != -1) {
res.edges.push_back(prev[t]);
assert(res.edges.size() < prev.size() && "path: negative cycle");
t = prev[t].src;
res.vertices.push_back(t);
}
std::reverse(res.vertices.begin(), res.vertices.end());
std::reverse(res.edges.begin(), res.edges.end());
return res;
}
};
namespace internal_shortest_path {
template <typename Cost>
ShortestPath<Cost> bfs(const Graph<Cost>& graph, long long s, Cost inf) {
std::vector<Cost> dist(graph.size(), inf);
std::vector<typename Graph<Cost>::Edge> prev(graph.size());
std::queue<long long> que;
dist[s] = 0;
que.push(s);
while (!que.empty()) {
long long u = que.front();
que.pop();
for (auto& e : graph[u]) {
if (dist[e.dst] == inf) {
dist[e.dst] = dist[e.src] + 1;
prev[e.dst] = e;
que.push(e.dst);
}
}
}
return {dist, prev};
}
// target が -1 でなければ、target の距離が決まった時点で打ち切る
template <typename Cost>
ShortestPath<Cost> dijkstra(const Graph<Cost>& graph, long long s, Cost inf, long long target = -1) {
for (long long v = 0; v < graph.size(); v++) {
for (const auto& e : graph[v]) assert(!(e.cost < Cost{}) && "negative edge (use shortest_path_bellman_ford)");
}
std::vector<Cost> dist(graph.size(), inf);
std::vector<typename Graph<Cost>::Edge> prev(graph.size());
using Node = std::pair<Cost, long long>;
std::priority_queue<Node, std::vector<Node>, std::greater<Node>> que;
dist[s] = 0;
que.push({0, s});
while (!que.empty()) {
auto [d, u] = que.top();
que.pop();
if (d > dist[u])
continue;
if (u == target) break;
for (auto& e : graph[u]) {
if (dist[e.dst] == inf || dist[e.dst] > dist[e.src] + e.cost) {
dist[e.dst] = dist[e.src] + e.cost;
prev[e.dst] = e;
que.push({dist[e.dst], e.dst});
}
}
}
return {dist, prev};
}
} // namespace internal_shortest_path
/**
* @brief s から t への最短路 (Dijkstra。t の距離が決まった時点で打ち切る) O(m log m)
*
* @return std::optional<Path<Cost>> 長さ、たどる頂点、たどる辺。届かなければ std::nullopt。s == t なら長さ 0、頂点は s だけ、辺は空
* @note 負の辺があると assert で落ちる (負の辺があるなら shortest_path_bellman_ford)
*/
template <typename Cost = long long>
std::optional<Path<Cost>> shortest_path(const Graph<Cost>& graph, long long s, long long t) {
assert(0 <= s && s < graph.size());
assert(0 <= t && t < graph.size());
return internal_shortest_path::dijkstra(graph, s, std::numeric_limits<Cost>::max() / 4, t).path(t);
}
/**
* @brief ある頂点から各頂点への最短路 (Dijkstra) O(m log m)
*
* @param s 始点
* @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
* @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
* @note 負の辺があると assert で落ちる (負の辺があるなら shortest_path_bellman_ford)
*/
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_dijkstra(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
assert(0 <= s && s < graph.size());
return internal_shortest_path::dijkstra(graph, s, inf);
}
/**
* @brief 辺の重みをすべて 1 とみなして、ある頂点から各頂点への最短路 (BFS) O(n + m)
*
* @param s 始点
* @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
* @return ShortestPath 各頂点への最短路長 (辺の本数、dist) と、各頂点への最短路上の直前の辺 (prev)
*/
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_bfs(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
assert(0 <= s && s < graph.size());
return internal_shortest_path::bfs(graph, s, inf);
}
/**
* @brief ある頂点から各頂点への最短路
*
* @param s 始点
* @param inf コストのminの単位元 未到達の頂点への距離はinfになる 省略すると std::numeric_limits<Cost>::max() / 4 負閉路の影響を受ける点は -inf
* @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
*/
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_bellman_ford(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
assert(0 <= s && s < graph.size());
const long long n = graph.size();
std::vector<Cost> dist(n, inf);
std::vector<typename Graph<Cost>::Edge> prev(n);
dist[s] = Cost{};
for (long long i = 1; i < n; i++) {
bool changed = false;
for (long long j = 0; j < n; j++)
for (const auto& e : graph[j]) {
if (dist[e.src] == inf)
continue;
if (dist[e.dst] > dist[e.src] + e.cost) {
dist[e.dst] = dist[e.src] + e.cost;
if (dist[e.dst] < -inf)
dist[e.dst] = -inf;
prev[e.dst] = e;
changed = true;
}
}
if (!changed)
break;
}
for (long long i = 0; i < n; i++) {
bool changed = false;
for (long long j = 0; j < n; j++)
for (const auto& e : graph[j]) {
if (dist[e.src] == inf)
continue;
if (dist[e.dst] > dist[e.src] + e.cost) {
dist[e.dst] = -inf;
prev[e.dst] = e;
changed = true;
}
}
if (!changed)
break;
}
return {dist, prev};
}
/**
* @brief 辺のコストが 0 か 1 だけのグラフで、ある頂点から各頂点への最短路 (01-BFS) O(n + m)
*
* @param s 始点
* @param inf 未到達の頂点への距離 省略すると std::numeric_limits<Cost>::max() / 4
* @return ShortestPath 各頂点への最短路長 (dist) と、各頂点への最短路上の直前の辺 (prev)
*/
template <typename Cost = long long>
ShortestPath<Cost> shortest_path_01bfs(const Graph<Cost>& graph, long long s, Cost inf = std::numeric_limits<Cost>::max() / 4) {
assert(0 <= s && s < graph.size());
std::vector<Cost> dist(graph.size(), inf);
std::vector<typename Graph<Cost>::Edge> prev(graph.size());
std::deque<long long> que;
dist[s] = 0;
que.push_back(s);
while (!que.empty()) {
long long u = que.front();
que.pop_front();
for (auto& e : graph[u]) {
assert(e.cost == 0 || e.cost == 1);
if (dist[e.dst] == inf || dist[e.dst] > dist[u] + e.cost) {
dist[e.dst] = dist[u] + e.cost;
prev[e.dst] = e;
if (e.cost == 0)
que.push_front(e.dst);
else
que.push_back(e.dst);
}
}
}
return {dist, prev};
}
/**
* @brief 全点対間の最短路長 (Floyd-Warshall) O(n^3)
*
* @param inf 未到達を表す値 省略すると std::numeric_limits<Cost>::max() / 4
* @return std::vector<std::vector<Cost>> dist[i][j] が i から j への最短路長 (到達できなければ inf)
* @note 負の辺があってもよい。dist[i][i] < 0 となる i があれば負閉路がある
* 負閉路があるときの値は -inf 以上に切り詰めるので、あふれない (負閉路の影響を受ける組の値は最短路長ではない)
*/
template <typename Cost = long long>
std::vector<std::vector<Cost>> shortest_path_floyd_warshall(const Graph<Cost>& graph, Cost inf = std::numeric_limits<Cost>::max() / 4) {
const long long n = graph.size();
std::vector<std::vector<Cost>> dist(n, std::vector<Cost>(n, inf));
for (long long i = 0; i < n; i++) dist[i][i] = Cost{};
for (long long i = 0; i < n; i++) {
for (auto& e : graph[i]) dist[i][e.dst] = std::min(dist[i][e.dst], e.cost);
}
for (long long k = 0; k < n; k++) {
for (long long i = 0; i < n; i++) {
if (dist[i][k] == inf) continue;
for (long long j = 0; j < n; j++) {
if (dist[k][j] == inf) continue;
// dist は -inf 以上 inf 以下なので、和は -2 inf 以上であふれない
Cost d = dist[i][k] + dist[k][j];
if (d < -inf) d = -inf;
if (d < dist[i][j]) dist[i][j] = d;
}
}
}
return dist;
}
#line 22 "test/unittest/graph/grid-graph.test.cpp"
using ll = long long;
using Cell = std::pair<ll, ll>;
static_assert(std::is_same_v<decltype(std::declval<const GridGraph&>().graph()), const Graph<ll>&>);
static_assert(std::is_same_v<decltype(std::declval<GridGraph&>().board()), const std::vector<std::string>&>);
static_assert(!std::is_assignable_v<decltype(std::declval<GridGraph&>().board()[0][0]), char>);
static_assert(!std::is_convertible_v<std::vector<std::string>, GridGraph>);
bool adjacent(Cell a, Cell b) {
return std::abs(a.first - b.first) + std::abs(a.second - b.second) == 1;
}
void verify(const GridGraph& maze, const std::vector<std::string>& board, char wall) {
const ll h = board.size(), w = board.empty() ? 0 : static_cast<ll>(board.front().size());
assert(maze.board() == board && maze.height() == h && maze.width() == w);
std::vector<Cell> cells;
for (ll i = 0; i < h; ++i) {
for (ll j = 0; j < w; ++j) {
const ll expected = board[i][j] == wall ? -1 : static_cast<ll>(cells.size());
assert(maze.index(i, j) == expected);
if (expected != -1) cells.emplace_back(i, j);
}
}
const ll n = cells.size();
assert(maze.size() == n && maze.graph().size() == n);
std::set<std::pair<ll, ll>> expected_edges, actual_edges;
for (ll u = 0; u < n; ++u) {
assert(maze.cell(u) == cells[u]);
assert(maze.label(u) == board[cells[u].first][cells[u].second]);
std::set<ll> expected_neighbors, actual_neighbors;
for (ll v = 0; v < n; ++v) {
if (adjacent(cells[u], cells[v])) {
expected_neighbors.insert(v);
if (u < v) expected_edges.emplace(u, v);
}
}
for (const auto& edge : maze[u]) {
assert(edge.src == u && edge.cost == 1 && 0 <= edge.dst && edge.dst < n);
actual_neighbors.insert(edge.dst);
}
assert(actual_neighbors == expected_neighbors && maze[u].size() == expected_neighbors.size());
assert(&maze[u] == &maze.graph()[u]);
}
assert(maze.graph().edge_count() == static_cast<ll>(expected_edges.size()));
std::vector<ll> edge_occurrences(maze.graph().edge_count());
for (ll u = 0; u < n; ++u) {
for (const auto& edge : maze[u]) {
assert(0 <= edge.id && edge.id < maze.graph().edge_count());
++edge_occurrences[edge.id];
}
}
for (ll count : edge_occurrences) assert(count == 2);
for (const auto& edge : maze.graph().edges()) actual_edges.emplace(std::min(edge.src, edge.dst), std::max(edge.src, edge.dst));
assert(actual_edges == expected_edges);
for (char c : {'S', 'G', '.', '#', 'a', 'X', '\0'}) {
std::vector<ll> expected;
for (ll v = 0; v < n; ++v) {
if (board[cells[v].first][cells[v].second] == c) expected.push_back(v);
}
const auto matches = maze.find_all(c);
assert(std::vector<ll>(matches.begin(), matches.end()) == expected);
assert(std::vector<ll>(matches.begin(), matches.end()) == expected);
assert(maze.find(c) == (expected.empty() ? -1 : expected.front()));
// 一時的な検索rangeがなくなっても、iteratorの走査状態は独立している。
auto it = maze.find_all(c).begin();
for (ll v : expected) {
auto independent = it;
decltype(it) assigned;
assigned = it;
assert(*it++ == v && *independent == v && *assigned == v);
++independent;
assert(independent == it);
}
assert(it == matches.end());
#if __cplusplus >= 202002L
static_assert(std::ranges::forward_range<decltype(matches)>);
auto selected = maze.find_all(c) | std::views::take(1);
std::vector<ll> first;
std::ranges::copy(selected, std::back_inserter(first));
assert(first == (expected.empty() ? std::vector<ll>{} : std::vector<ll>{expected.front()}));
#endif
}
// Gridを使わず、座標のマンハッタン距離だけで隣接を判定するBFSと比較する。
const ll inf = std::numeric_limits<ll>::max() / 4;
for (ll s = 0; s < n; ++s) {
std::vector<ll> expected(n, inf);
std::queue<ll> queue;
expected[s] = 0;
queue.push(s);
while (!queue.empty()) {
const ll u = queue.front();
queue.pop();
for (ll v = 0; v < n; ++v) {
if (expected[v] != inf || !adjacent(cells[u], cells[v])) continue;
expected[v] = expected[u] + 1;
queue.push(v);
}
}
const auto result = shortest_path_bfs(maze.graph(), s);
assert(result.dist == expected);
for (ll t = 0; t < n; ++t) {
const auto path = result.path(t);
assert(path.has_value() == (expected[t] != inf));
if (path) {
assert(path->vertices.front() == s && path->vertices.back() == t);
assert(path->cost == expected[t] && static_cast<ll>(path->edges.size()) == expected[t]);
for (ll i = 1; i < static_cast<ll>(path->vertices.size()); ++i) {
assert(adjacent(maze.cell(path->vertices[i - 1]), maze.cell(path->vertices[i])));
}
}
}
}
}
int main() {
for (const auto& board : std::vector<std::vector<std::string>>{
{}, {"", ""}, {"#"}, {"."}, {"S"}, {"###", "###"}, {"S#G"}, {"S", "#", "G"}, {"S..#.", ".#...", "...G."}, {"aaa", "a#a", "aaa"}}) {
verify(GridGraph(board), board, '#');
}
verify(GridGraph({"S#XG", "aX.a"}, 'X'), {"S#XG", "aX.a"}, 'X');
verify(GridGraph({"S.G"}, 'S'), {"S.G"}, 'S');
const std::vector<std::string> binary = {std::string("a\0#", 3)};
verify(GridGraph(binary), binary, '#');
{
const std::vector<std::string> expected = {"S..#.", ".#...", "...G."};
auto input = expected;
GridGraph maze(input);
input.clear();
verify(maze, expected, '#');
const GridGraph copy(maze);
verify(copy, expected, '#');
GridGraph moved(std::move(maze));
verify(moved, expected, '#');
assert(shortest_path_bfs(moved.graph(), moved.find('S')).dist[moved.find('G')] == 5);
}
std::mt19937 rng(314);
for (int rep = 0; rep < 600; ++rep) {
const ll h = rng() % 8, w = rng() % 8;
std::vector<std::string> board(h, std::string(w, '.'));
for (auto& row : board) {
for (char& c : row) c = std::string("##..aSGX")[rng() % 8];
}
const char wall = rep % 2 == 0 ? '#' : 'X';
verify(GridGraph(board, wall), board, wall);
}
std::cout << "Hello World\n";
}