題目說明#
給你一個 \(n \times n\) 的圖,請你以龍捲風方式輸出
解題過程#
本題只需照題目要求實作即可
於是我們來思考如何實作
首先我們從中點出發,座標是\(( \frac{n}{2} , \frac{n}{2} )\),接著有四個方向,
照著題目的定義:
0代表左,1代表上,2代表右,3代表下
接著我們可以發現,移動方向的順序會是 左->上->右->下->左
剛好跟題目的定義可以對照成 0->1->2->3->0!
於是我們可以發現,假設現在的方向為d,那麼下一個方向就會是 \((d + 1) % 4\)!
故我們使用一個pair陣列,將我們的移動方向放進去
pair<int, int> dir[4] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
(dir的第0項便是方向0,向左,每移動一次都是y座標-1)
這樣可以使我們等下移動座標時更為簡單,只需要 “目前座標 += dir[方向]“即可
接著我們觀察每次同方向移動的步數,可以發現是 1->1->2->2->3->3….
而最後一步會少移動一格! 例如3x3會是 1->1->2->2->“2”,4x4則是 1->1->2->2->3->3->“3”
所以我們可以很簡單的利用迴圈做到上面的事,只需要特別分開最後一步即可!
整理一下最後的流程
- 走x格
- 方向 = (方向+1)%4
- 走x格
- 方向 = (方向+1)%4
- x = x+1
直到 x=n-1,再走n-1格。
AC Code#
#include <bits/stdc++.h>
using namespace std;
pair<int, int> dir[4] = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
signed main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
int mp[n][n];
for(int x=0; x<n; x++){
for(int y=0; y<n; y++){
cin >> mp[x][y];
}
}
pair<int, int> pos = {n/2, n/2};
cout << mp[pos.first][pos.second];
for(int x=0; x<2*(n-1); x++){
for(int y=0; y<(x/2+1); y++){ //注意這邊是利用x/2+1控制移動步數,可以試著自己推推看
pos = {pos.first+dir[m].first, pos.second+dir[m].second}; //沿著目前方向走一步
cout << mp[pos.first][pos.second]; //輸出
}
m = (m+1)%4; //改變方向
}
//最後再走n-1步
for(int y=0; y<n-1; y++){
pos = {pos.first+dir[m].first, pos.second+dir[m].second};
cout << mp[pos.first][pos.second];
}
return 0;
}
