#54509: C++ 解答


kita197 (KK)


//使用GPT

#include <bits/stdc++.h>
using namespace std;

int main(){
    vector<string> board(9);
    for(int i = 0; i < 9; i++){
        cin >> board[i];
    }

    int dr[4] = {1, -1, 0, 0};
    int dc[4] = {0, 0, 1, -1};

    vector<vector<bool>> vis(9, vector<bool>(9, false));

    int scoreB = 0, scoreW = 0;

    // ① 先統計棋子數
    for(int i = 0; i < 9; i++){
        for(int j = 0; j < 9; j++){
            if(board[i][j] == 'B') scoreB++;
            else if(board[i][j] == 'W') scoreW++;
        }
    }

    // ② 掃描每一塊空地
    for(int i = 0; i < 9; i++){
        for(int j = 0; j < 9; j++){
            if(board[i][j] == '.' && !vis[i][j]){
                queue<pair<int,int>> q;
                vector<pair<int,int>> territory;

                q.push({i, j});
                vis[i][j] = true;
                territory.push_back({i, j});

                bool touchB = false, touchW = false;

                while(!q.empty()){
                    auto [r, c] = q.front();
                    q.pop();

                    for(int k = 0; k < 4; k++){
                        int nr = r + dr[k];
                        int nc = c + dc[k];

                        if(nr < 0 || nr >= 9 || nc < 0 || nc >= 9) continue;

                        if(board[nr][nc] == '.' && !vis[nr][nc]){
                            vis[nr][nc] = true;
                            q.push({nr, nc});
                            territory.push_back({nr, nc});
                        }
                        else if(board[nr][nc] == 'B'){
                            touchB = true;
                        }
                        else if(board[nr][nc] == 'W'){
                            touchW = true;
                        }
                    }
                }

                // 同時被黑白包圍 → Wrong
                if(touchB && touchW){
                    cout << "Wrong\n";
                    return 0;
                }

                // 只屬於一方
                if(touchB){
                    scoreB += territory.size();
                    for(auto &p : territory){
                        board[p.first][p.second] = 'B';
                    }
                }
                else if(touchW){
                    scoreW += territory.size();
                    for(auto &p : territory){
                        board[p.first][p.second] = 'W';
                    }
                }
            }
        }
    }

    // ③ 輸出結果
    if(scoreB > scoreW) cout << "Black wins!!\n";
    else cout << "White wins!!\n";

    cout << scoreB << ":" << scoreW << "\n";

    for(int i = 0; i < 9; i++){
        cout << board[i] << "\n";
    }

    return 0;
}