解題思路
將每行×所在欄號轉成布林棋盤,其餘為○。
對水平、垂直、兩斜向各方向,只從其前一格已在棋盤外的位置開始,沿方向走到底,得到唯一最大線段。
長度至少3且全部符號相同才保留,兩端點正規化後排序輸出。每個方向的最大線有唯一邊界起點,因此不會把一條線的子段重算。
時間 O(n²),空間 O(n²),n≤10。
Step-by-step animation
教學小例:枚舉四方向的完整最大線段
步驟 1 / 3
3×3全○
三橫、三直皆同符號
三橫、三直皆同符號
- 步驟
- 1
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
string s;
getline(cin, s);
vector<vector<int>> a(n, vector<int>(n));
for (int y = 0; y < n; y++) {
getline(cin, s);
stringstream ss(s);
int x;
while (ss >> x)
if (x)
a[y][x - 1] = 1;
}
vector<array<int, 4>> out;
auto in = [&](int x, int y) { return x >= 0 && x < n && y >= 0 && y < n; };
for (auto [dx, dy] : vector<pair<int, int>>{{1, 0}, {0, 1}, {1, 1}, {1, -1}})
for (int y = 0; y < n; y++)
for (int x = 0; x < n; x++)
if (!in(x - dx, y - dy)) {
int u = x, v = y, len = 0;
bool ok = true;
pair<int, int> end;
while (in(u, v)) {
ok &= a[v][u] == a[y][x];
end = {u, v};
len++;
u += dx;
v += dy;
}
if (ok && len >= 3) {
pair<int, int> b = {x + 1, y + 1},
c = {end.first + 1, end.second + 1};
if (c < b)
swap(b, c);
out.push_back({b.first, b.second, c.first, c.second});
}
}
sort(out.begin(), out.end());
cout << out.size() << '\n';
for (auto [x, y, u, v] : out)
cout << '(' << x << ',' << y << ")(" << u << ',' << v << ")\n";
}
先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。