解題思路
對每個中心格與四個可能缺少的方向,取中心加其他三個鄰格。
只有四格都在範圍內且皆為O才保留;每種T形有唯一中心與缺方向,因此不會重複產生。
各形內座標先依(x,y)排序,再將所有形依座標串列排序,照題目保留座標前後空白。
時間 O(HW)固定四方向;儲存結果空間 O(HW)。
Step-by-step animation
教學小例:枚舉T形中心與缺少方向
步驟 1 / 3
3×3只有第一列OOO與中心O
選中心(1,0)
選中心(1,0)
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
int h, w;
cin >> h >> w;
vector<string> a(h);
for (auto &s : a)
cin >> s;
vector<vector<pair<int, int>>> ans;
vector<pair<int, int>> ds = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int y = 0; y < h; y++)
for (int x = 0; x < w; x++)
for (int omit = 0; omit < 4; omit++) {
vector<pair<int, int>> v = {{x, y}};
for (int d = 0; d < 4; d++)
if (d != omit)
v.push_back({x + ds[d].first, y + ds[d].second});
bool ok = true;
for (auto [c, r] : v)
if (c < 0 || c >= w || r < 0 || r >= h || a[r][c] != 'O')
ok = false;
if (ok) {
sort(v.begin(), v.end());
ans.push_back(v);
}
}
sort(ans.begin(), ans.end());
cout << ans.size() << '\n';
for (auto v : ans) {
for (auto [x, y] : v)
cout << " (" << x << ',' << y << ") ";
cout << '\n';
}
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。