b264中等

99 台中區資訊學科能力競賽(2010)|細胞生命遊戲

輸出第2至5代棋盤及活細胞數。

解題思路

輸出第2至5代棋盤及活細胞數。

每一格計算八方向內仍在棋盤中的活鄰居,不環繞;活格有2或3個活鄰居存活,死格只有恰3個鄰居復活。

每一代必須寫入新棋盤,整代算完才能替換舊棋盤,避免先更新的格影響同一代其他格。

逐格套用規則即可由上一代唯一決定下一代,重複四次恰得到要求世代。

固定棋盤與四次更新,時間與空間皆 O(1)。

Step-by-step animation

5×5中央三連細胞的週期示例

回報動畫錯誤
步驟 1 / 3

步驟 1

示例水平三連活格,周圍皆0。

00000
00000
01110
00000
00000
步驟
1

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    vector<vector<int>> a(5, vector<int>(5));
    char c;
    for (auto &r : a)
        for (int &x : r) {
            cin >> c;
            x = c - '0';
            if (cin.peek() == ',')
                cin.get();
        }
    for (int g = 2; g <= 5; g++) {
        auto b = a;
        int total = 0;
        for (int i = 0; i < 5; i++)
            for (int j = 0; j < 5; j++) {
                int t = 0;
                for (int u = max(0, i - 1); u <= min(4, i + 1); u++)
                    for (int v = max(0, j - 1); v <= min(4, j + 1); v++)
                        if (u != i || v != j)
                            t += a[u][v];
                b[i][j] = (t == 3 || (a[i][j] && t == 2));
                total += b[i][j];
            }
        a = b;
        cout << "第" << g << "代: " << total << "個細胞存活\n";
        for (auto r : a) {
            for (int j = 0; j < 5; j++)
                cout << (j ? "," : "") << r[j];
            cout << '\n';
        }
    }
}

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

更多