yukicoder No.348 カゴメカゴメ
デバッグに手間取った
追記:この解説のコードはチャレンジによって落とされました
(2回連続輪を塗らない方がいい場合に対応できてません)
http://yukicoder.me/problems/795
問題
注意点としては"x"は必ずある1つの輪に属しているという条件がある。したがって異なる輪間にはかならず隙間が存在することと輪の親となる輪は1つしかないことがわかる。
解法
ある輪を囲む輪の数をその輪の深さと定義する。
まず処理を簡単にするためグリッドを"."で囲んでおく。
グリッドを走査していき、深さがわかっていない"."な点を訪れたらdfsにより連結な点を(1つ外の輪の深さ)+1とする。
また、まだ調べていない輪を訪れたらdfsで輪の大きさを数える。
あとは奇数の深さと偶数の深さにある輪の大きさの総和のうち、大きい方を出力すればいい。
#include <bits/stdc++.h> using namespace std; typedef long long ll; #define REP(i, a, b) for (int i = (int)(a); i < (int)(b); i++) #define rep(i, a) REP(i, 0, a) int dx4[] = {1, 0, -1, 0}, dy4[] = {0, 1, 0, -1}; int dx8[] = {1, 1, 0, -1, -1, -1, 0, 1}, dy8[] = {0, 1, 1, 1, 0, -1, -1, -1}; int N, M; char G[1005][1005]; int depth[1005][1005]; int ans[2]; bool is_inside(int x, int y) { return (0 <= x && x < M && 0 <= y && y < N); } int dfs_x(int x, int y) { G[y][x] = 'X'; int res = 1; rep(i, 8) { int nx = x + dx8[i], ny = y + dy8[i]; if (!is_inside(nx, ny)) continue; if (G[ny][nx] != 'x') continue; res = dfs_x(nx, ny) + 1; } return res; } void dfs_dot(int x, int y, int d) { depth[y][x] = d; rep(i, 4) { int nx = x + dx4[i], ny = y + dy4[i]; if (!is_inside(nx, ny)) continue; if (G[ny][nx] != '.') continue; if (depth[ny][nx] != -1) continue; dfs_dot(nx, ny, d); } } int main(void) { cin >> N >> M; // グリッドを'.'で囲んでおく rep(y, N + 2) rep(x, M + 2) G[y][x] = '.'; rep(y, N) rep(x, M) cin >> G[y + 1][x + 1]; rep(y, N + 2) rep(x, M + 2) depth[y][x] = -1; N += 2; M += 2; int d = -1; //輪の深さ rep(y, N) rep(x, M) { if (G[y][x] == 'x') { ans[d%2] += dfs_x(x, y); //輪の大きさを数える } if (G[y][x] == '.') { if (depth[y][x] == -1) dfs_dot(x, y, d + 1); //深さを設定する d = depth[y][x]; } } cout << max(ans[0], ans[1]) << endl; return 0; }