a434中等矩陣座標・順時針螺旋
APCS 2017/03:數字龍捲風 (ZeroJudge c292)
以方向向量與兩段一組的步長,從中央走訪全部格子。
這題在學什麼
中央格的 0 起算座標是 (N//2,N//2),必須在移動前先輸出。依題意把方向編成左、上、右、下,向量依序為 (0,−1)、(−1,0)、(0,1)、(1,0);方向編號加 1 取模 4 就是右轉。
每個長度連走兩段:1 步、1 步後改為 2 步、2 步,再改為 3 步、3 步。每段完成才轉向,不是每走一步就轉。這些折線一圈圈包住已讀區域,不會重訪舊格。
走到 N² 個數字便立即停止,即使最後一段尚未走完也不再踏出下一步。奇數方陣的這條路徑在此前都位於矩陣內,並覆蓋全部格子。將數字直接串接,符合輸出不加空白的要求。
Step-by-step animation
公開範例二:3×3,起始向上
步驟 1 / 4
讀中央
矩陣列為 412/305/678,中央值是 0。
4
1
2
3
0
5
6
7
8
- 座標
- (1,1)
- 輸出
- 0
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int n, direction;
cin >> n >> direction;
vector<vector<int>> grid(n, vector<int>(n));
for (auto &row : grid) for (int &value : row) cin >> value;
const int dr[4] = {0, -1, 0, 1};
const int dc[4] = {-1, 0, 1, 0};
int r = n / 2, c = n / 2;
string output(1, char('0' + grid[r][c]));
for (int length = 1; int(output.size()) < n * n; ++length) {
for (int segment = 0; segment < 2; ++segment) {
for (int step = 0; step < length; ++step) {
if (int(output.size()) == n * n) break;
r += dr[direction];
c += dc[direction];
output += char('0' + grid[r][c]);
}
direction = (direction + 1) % 4;
}
}
cout << output << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。