#15289: 平凡解法


lambertWu (Lambert)

學校 : 義守大學I-Shou University
編號 : 85456
來源 : [218.173.20.182]
最後登入時間 :
2019-11-16 02:29:21
a417. 螺旋矩陣 | From: [114.40.195.130] | 發表日期 : 2018-09-26 18:25

觀察行走方向後,可以知道到最邊邊之後都會轉固定的方向
順時針: 右轉下,下轉左,左轉上,上轉右
逆時針: 下轉右,右轉上,上轉左,左轉下


#include <iostream>
#include <iomanip>

using namespace std;


int main() {

enum direction {top, down, left, right};
enum rotate {clockwise = 1, counterclockwise};
int count,n,rot;
int grid[100][100];

while (cin >> count){
while (count){
cin >> n >> rot;
int row = 0, col = 0;
int dir = rot==clockwise?right:down;
// 矩陣的最邊邊,轉向判斷用
int t = 1, d = n,
l = 0, r = n;

if(rot==counterclockwise){
l = 1;
t = 0;
}

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
int val = (i*n) + (j + 1);
grid[row][col] = val;

switch (dir){
case top:
row--;
if(row == t){
if(rot == clockwise)
dir = right;
else
dir = left;
t++;
}
break;
case down:
row++;
if(row+1 >= d) {
d--;
dir = rot==clockwise?left:right;
}
break;
case left:
col--;
if(col == l){
if(rot == clockwise)
dir = top;
else
dir = down;
l++;
}
break;
case right:
col++;
if(col+1 >= r){
r--;
dir = rot==clockwise?down:top;
}
break;
}
}
}

for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j)
cout << setw(5) << grid[i][j];
cout << endl;
}

count--;
}
}

return 0;
}
 
ZeroJudge Forum