P 5731【深基5.習6】蛇形方陣[c++版]
タイトルリンク
https://www.luogu.com.cn/problem/P5731トランスファゲート
タイトルの説明
9以下の正の整数nnを与え、nを出力する.×nの蛇形方陣.
左上隅に1を記入してから、サンプルのように時計回りに順番に数字を記入します.注意各数字には3文字が使用され、前にスペースを使用して整列します.
入力フォーマット
なし
出力フォーマット
なし
入出力サンプル
入力#1
出力#1
ヒント
list[1][1]から、右シフト/下シフト/左シフト/上シフトの過程で、2つの判断点:1.境界を越えるかどうか、すなわち次の下付き記号は[1,n]の間にあるべきである.2.Null値であるかどうか、つまり次の値は0であるべきで、値を割り当て続けることができます.いずれも次の配列要素に値を割り当てるため、++xの操作を採用します.
コード#コード#
https://www.luogu.com.cn/problem/P5731トランスファゲート
タイトルの説明
9以下の正の整数nnを与え、nを出力する.×nの蛇形方陣.
左上隅に1を記入してから、サンプルのように時計回りに順番に数字を記入します.注意各数字には3文字が使用され、前にスペースを使用して整列します.
入力フォーマット
なし
出力フォーマット
なし
入出力サンプル
入力#1
4
出力#1
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
ヒント
list[1][1]から、右シフト/下シフト/左シフト/上シフトの過程で、2つの判断点:1.境界を越えるかどうか、すなわち次の下付き記号は[1,n]の間にあるべきである.2.Null値であるかどうか、つまり次の値は0であるべきで、値を割り当て続けることができます.いずれも次の配列要素に値を割り当てるため、++xの操作を採用します.
コード#コード#
#include
#include
using namespace std;
int list[20][20] = {
0};
int main(){
int n,x = 1,y = 0;
cin >> n;
int k = 1;
while(k<=n*n){
while(y < n && list[x][y + 1] == 0) list[x][++y] = k++;
while(x < n && list[x + 1][y] == 0) list[++x][y] = k++;
while(y > 1 && list[x][y - 1] == 0) list[x][--y] = k++;
while(x > 1 && list[x - 1][y] == 0) list[--x][y] = k++;
}
for(int i = 1;i <= n;i++){
for(int j = 1;j <= n;j++){
printf("%3d",list[i][j]);
}
cout << endl;
}
}