回字型数字方阵
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int calculate_value(int, int, int);
void print_matrix(int);
void main()
{
int n;
scanf("%d", &n);
print_matrix(n);
}
void print_matrix(int n)
{
register int i, j;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
printf("%d\t", calculate_value(n, i, j));
}
printf("\n");
}
}
int calculate_value(int n, int row, int col)
{
int cur_val = 1, cur_row = 1, cur_col = 1;
int right_bound=n, lower_bound=n, left_bound=1, upper_bound=1;
register int direction=6;//right:6 down:2 left:4 up:8
while (cur_row != row || cur_col != col)
{
switch (direction)
{
right:case 6:
if (cur_col < right_bound)
{
cur_col++;
cur_val++;
}
if (cur_col == right_bound)
{
upper_bound++;
direction = 2;
}
break;
down:case 2:
if (cur_row < lower_bound)
{
cur_row++;
cur_val++;
}
if (cur_row == lower_bound)
{
right_bound--;
direction = 4;
}
break;
left:case 4:
if (cur_col > left_bound)//这里不能是一个常量1,而应该是一个随着发展而变化的变量
{
cur_col--;
cur_val++;
}
if (cur_col == left_bound)
{
lower_bound--;
direction = 8;
}
break;
up:case 8:
if (cur_row > upper_bound)
{
cur_row--;
cur_val++;
}
if (cur_row == upper_bound)
{
left_bound++;
direction = 6;
}
break;
}
}
return cur_val;
}