蓝桥杯2011年编程大题
8.程序设计(满分15分)
方阵的主对角线之上称为“上三角”。
请你设计一个用于填充n阶方阵的上三角区域的程序。填充的规则是:使用1,2,3….的自然数列,从左上角开始,按照顺时针方向螺旋填充。
例如:当n=3时,输出:
1 2 3
6 4
5
当n=4时,输出:
1 2 3 4
9 10 5
8 6
7
当n=5时,输出:
1 2 3 4 5
12 13 14 6
11 15 7
10 8
9
程序运行时,要求用户输入整数n(3~20)
程序输出:方阵的上三角部分。
要求格式:每个数据宽度为4,右对齐。
简单的模拟题。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int n;
int val[22][22];
//chance 0向右 1向左下 2向上
void triangle(int sum, int step, int x, int y, int chance){
val[x][y] = step;
if(step == sum){
return;
}
if(chance == 0){//向右
if(step < n){//第一行特判
triangle(sum, step + 1, x, y + 1, chance);
} else if (step == n){//第一行特判
triangle(sum, step + 1, x + 1, y - 1, 1);
} else if (val[x][y + 1] == 0){//判断是否已有数字存在
triangle(sum, step + 1, x, y + 1, chance);
} else {
triangle(sum, step + 1, x + 1, y - 1, 1);
}
} else if(chance == 1) {//向左下
if(y - 1 <= 0 || val[x + 1][y - 1]){//判断是否越界 || 是否已有数字存在
triangle(sum, step + 1, x - 1, y, 2);
}else{
triangle(sum, step + 1, x + 1, y - 1, 1);
}
} else if(chance == 2) {//向上
if(val[x - 1][y]){//判断是否已有数字存在
triangle(sum, step + 1, x, y + 1, 0);
} else {
triangle(sum, step + 1, x - 1, y, 2);
}
}
}
int main(){
memset(val, 0, sizeof(val));//初始化
cin >> n;
triangle(((1 + n) * n) / 2, 1, 1, 1, 0);
for(int i = 1; i <= n; ++i){
for(int j = 1; j <= n - i + 1; ++j){
printf("%4d", val[i][j]);//格式化输出
if(j != n - i + 1){
cout << ' ';
}
}
cout << endl;
}
return 0;
}