b331中等

95 臺北市資訊學科能力競賽(2006)|井字遊戲

統計從指定井字棋局可達的不同終局。

解題思路

統計從指定井字棋局可達的不同終局。

從目前棋盤出發,每步先判斷是否已有三連勝;若有勝者或已滿盤,保存為終局,不再落子。

否則根據O與X數量決定下一位,在每個空格試落一子。以棋盤字串作已訪集合,避免不同落子順序重複探索同一局面。

每個合法延伸都被枚舉,且遇勝立即停止;終局集合依O勝、X勝或平手分類即可,不同落子順序不重複計。

最多3^9個棋盤,時間 O(9×3^9),空間 O(3^9);固定大小可視為常數。

Step-by-step animation

OO-XX----的分支及終局停止示例

回報動畫錯誤
步驟 1 / 3

步驟 1

示例OO-XX----,目前O走。

OO-
XX-
---
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    string s;
    cin >> s;
    set<string> seen;
    int ans[3] = {};
    int lines[8][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6},
                       {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6}};
    function<void(string)> go = [&](string a) {
        if (!seen.insert(a).second)
            return;
        for (auto &l : lines)
            if (a[l[0]] != '-' && a[l[0]] == a[l[1]] && a[l[1]] == a[l[2]]) {
                ans[a[l[0]] == 'O' ? 0 : 1]++;
                return;
            }
        if (a.find('-') == string::npos) {
            ans[2]++;
            return;
        }
        char turn = count(a.begin(), a.end(), 'O') == count(a.begin(), a.end(), 'X')
                        ? 'O'
                        : 'X';
        for (int i = 0; i < 9; i++)
            if (a[i] == '-') {
                a[i] = turn;
                go(a);
                a[i] = '-';
            }
    };
    go(s);
    cout << ans[0] + ans[1] + ans[2] << ' ' << ans[0] << ' ' << ans[1] << ' ' << ans[2]
         << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多