// No.157 2つの空洞 // https://yukicoder.me/problems/no/157 // #include #include #include #include #include #include using namespace std; // グラフ問題用。 struct edge { int to; int cost; }; typedef pair P; // 最短距離と頂点の番号 const int INF = 999999999; // エッジが無いことを示す数字 vector dijkstra(vector>& adj, int s); int solve(vector> &maze, unsigned int W, unsigned int H); vector> prepare_graph(vector> &maze, unsigned int W, unsigned int H); int main() { std::cin.tie(nullptr); std::ios::sync_with_stdio(false); unsigned int W, H; cin >> W >> H; vector> maze(H); for (auto y = 0; y < H; ++y) { maze[y].resize(W); for (auto x = 0; x < W; ++x) cin >> maze[y][x]; } int ans = solve(maze, W, H); cout << ans << endl; } int solve(vector> &maze, unsigned int W, unsigned int H) { vector> adj = prepare_graph(maze, W, H); bool found = false; int start_node; for (auto y = 1; y < H-1; y++) { if (found) break; for (auto x = 1; x < W - 1; ++x) { if (maze[y][x] == '.') { found = true; start_node = W * y + x; break; } } } vector dist = dijkstra(adj, start_node); for (auto y = 1; y < H-1; ++y){ for (auto x = 1; x < W-1; ++x) { int ans = dist[W*y + x]; if (ans != 0 && maze[y][x] != '#') return ans; } } } vector> prepare_graph(vector> &maze, unsigned int W, unsigned int H) { vector> adj(W * H); vector dx = {0, 0, -1, 1}; vector dy = {-1, 1, 0, 0}; for (auto y = 1; y < H-1; ++y) { for (auto x = 1; x < W-1; ++x) { for (auto i = 0; i < dx.size(); ++i) { int nx = x + dx[i]; int ny = y + dy[i]; if (0 < nx && nx < W-1 && 0 < ny && ny < H-1) { int from_node = W * y + x; int to_node = W * ny + nx; int cost = 1; if (maze[ny][nx] == '.') cost = 0; adj[from_node].push_back({to_node, cost}); } } } } return adj; } vector dijkstra(vector>& adj, int s) { // 隣接リスト(各ノードごとのedgeのベクトル)を使用して、ノードsからの最短距離を計算する vector d(adj.size()+1); // 各ノードまでの距離距離 fill(d.begin(), d.end(), INF ); // デフォルトではINFで埋めておく priority_queue, greater

> que; // firstが小さい順に取り出せるようにした優先度キュー d[s] = 0; // 自分への距離は0 que.push(P(0, s)); while (!que.empty()) { P p = que.top(); que.pop(); int v = p.second; if (d[v] < p.first) continue; for (int i = 0; i < adj[v].size(); ++i) { edge e = adj[v][i]; if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; que.push(P(d[e.to], e.to)); } } } return d; // 最終的な距離情報 }