#include "testlib.h"
#include <vector>
#include <string>
#include <queue>
using namespace std;

int main(int argc, char* argv[]) {
    setName("Keeping Cows Checker");
    registerTestlibCmd(argc, argv);

    // 读取输入：目标面积 a
    int a = inf.readInt();

    // 读取选手输出：h, w
    int h = ouf.readInt(1, 100, "h");
    int w = ouf.readInt(1, 100, "w");

    // 读取网格
    vector<string> grid(h);
    for (int i = 0; i < h; i++) {
        string line = ouf.readToken();
        if ((int)line.size() != w)
            quitf(_wa, "Line %d length is %d, expected %d", i + 1, (int)line.size(), w);
        for (char ch : line) {
            if (ch != '.' && ch != '#' && ch != 'O')
                quitf(_wa, "Invalid character '%c' at line %d", ch, i + 1);
        }
        grid[i] = line;
    }

    // 检查是否有多余 token
    ouf.skipBlanks();
    if (!ouf.eof()) {
        string extra = ouf.readToken();
        quitf(_wa, "Extra token found: '%s'", extra.c_str());
    }

    // BFS 检查是否存在一个大小为 a 且被围栏完全包围的 '.' 连通块
    vector<vector<bool>> vis(h, vector<bool>(w, false));
    int dx[4] = {-1, 1, 0, 0};
    int dy[4] = {0, 0, -1, 1};

    bool found = false;

    for (int i = 0; i < h && !found; i++) {
        for (int j = 0; j < w && !found; j++) {
            if (grid[i][j] == '.' && !vis[i][j]) {
                // BFS 当前连通块
                queue<pair<int,int>> q;
                q.push({i, j});
                vis[i][j] = true;
                vector<pair<int,int>> cells;
                bool valid = true;

                while (!q.empty()) {
                    auto [x, y] = q.front(); q.pop();
                    cells.push_back({x, y});

                    for (int dir = 0; dir < 4; dir++) {
                        int nx = x + dx[dir];
                        int ny = y + dy[dir];
                        if (nx < 0 || nx >= h || ny < 0 || ny >= w) {
                            // 越界 => 该区域没有围栏包围，非法
                            valid = false;
                        } else if (grid[nx][ny] == '.') {
                            if (!vis[nx][ny]) {
                                vis[nx][ny] = true;
                                q.push({nx, ny});
                            }
                        } else {
                            // 围栏（'#' 或 'O'），合法
                        }
                    }
                }

                int size = (int)cells.size();
                if (size == a && valid) {
                    found = true;
                }
                // 注意：如果 size != a 但 valid，可以忽略，但这里不处理。
            }
        }
    }

    if (found)
        quitf(_ok, "Found a valid fenced area of size %d", a);
    else
        quitf(_wa, "No valid fenced area of size %d found", a);
}
