C.蛇形阵
Description
蛇形针回字阵:
如3*3:
回字阵:
7 6 5
8 1 4
9 2 3
Input
多组数据:
每一行一个正整数n(n为奇数,<26),代表n*n矩阵。
Output
输出回字阵(字段宽度为4).
Sample Input 1
5
Sample Output 1
21 20 19 18 17
22 7 6 5 16
23 8 1 4 15
24 9 2 3 14
25 10 11 12 13
思路
一种是从1出发,另一种是从n*n出发,后者相比更简单写
以5×5为例
定义数组num[5][5],那么便是num[4][0]=25,设坐标为(x,y)
易于发现规律
坐标先向上运动,再向右运动,再向下运动,最后向左运动
剩下的就是循环往复,终止条件是最后输入数组的数字等于1时
对于向上运动便是x-1,y不变,那么终止条件便是x-1<0,且x-1,y对应坐标位置是空的
对于向右运动便是x不变,y+1,那么终止条件便是y+1>=n(越界),且x,y+1对应坐标位置是空的
对于向下动便是x+1,y不变,那么终止条件便是n+1>=n(越界),且x+1,y对应坐标位置是空的
对于向左运动便是x不变,y-1,那么终止条件便是y-1<0(越界),且x,y-1对应坐标位置是空的
代码
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
while (cin >> n) {
int num[26][26] = {};
int number = n * n;
num[n-1][0] = number;
int x = n - 1;
int y = 0;
while (number>1) {
while ((x - 1 >= 0) && (!num[x - 1][y])) {
num[--x][y] = --number;
}
while ((y + 1 < n) && (!num[x][y + 1])) {
num[x][++y] = --number;
}
while ((x + 1 < n) && (!num[x+1][y])) {
num[++x][y] = --number;
}
while ((y - 1 >= 0) && (!num[x][y-1])) {
num[x][--y] = --number;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << setw(4) << num[i][j];
}
cout << endl;
}
}
return 0;
}