a193簡單二維陣列、座標與鄰居

TOI 2020/12 新手組:舉旗遊戲

每格在原隊形中找相同旗色的八方向鄰居。

前往題目練習 →回報教學錯誤時間 O(RC),空間 O(RC)。

這題在學什麼

對每個學生列舉 dr、dc 屬於 -1、0、1 的位移,跳過 (0,0)。

只檢查仍在隊伍範圍內的位置;找到任一同色鄰居就不淘汰。

沒有同色鄰居才加到答案,判斷過程不修改原矩陣。

Step-by-step animation

舉旗遊戲・八鄰格同色判定

回報動畫錯誤
步驟 1 / 3

檢查旗子 1

所有 1 都至少鄰接另一個 1,包含對角方向。

1 1 2
1 1 1
2 1 2
旗色 1 淘汰數
0

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int r, c;
    cin >> r >> c;
    vector<vector<int>> a(r, vector<int>(c));
    for (auto &row : a)
        for (int &x : row)
            cin >> x;
    int ans = 0;
    for (int i = 0; i < r; i++)
        for (int j = 0; j < c; j++) {
            bool same = false;
            for (int dr = -1; dr <= 1; dr++)
                for (int dc = -1; dc <= 1; dc++) {
                    int x = i + dr, y = j + dc;
                    if ((dr || dc) && x >= 0 && x < r && y >= 0 && y < c &&
                        a[x][y] == a[i][j])
                        same = true;
                }
            if (!same)
                ++ans;
        }
    cout << ans << '\n';
}

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

更多