蛇形填数
-
描述
-
在n*n方陈里填入1,2,...,n*n,要求填成蛇形。例如n=4时方陈为:
10 11 12 1
9 16 13 2
8 15 14 3
7 6 5 4
-
输入
- 直接输入方陈的维数,即n的值。(n<=100) 输出
- 输出结果是蛇形方陈。 样例输入
-
3
样例输出
-
7 8 1 6 9 2 5 4 3
思想:定义四个数top, bottom, left, right来表示矩阵的最外围四个面的索引值,在迭代过程中使top和bottom、left和right逐步靠近,直到相等则迭代结束。
代码实现如下:
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int a[100][100];
//分别定义四个方位的索引值大小,使矩阵不断向中间缩小,从外围向中间填满
int top = 0, bottom = n - 1, left = 0, right = n - 1;
int num = 1;
while (top <= bottom && left <= right)
{
//最右侧一列
for (int i = top; i <= bottom; i++)
{
a[i][right] = num;
num++;
}
right--;
//最底端一行
for (int i = right; i >= left; i--)
{
a[bottom][i] = num;
num++;
}
bottom--;
//最左侧一列
for (int i = bottom; i >= top; i--)
{
a[i][left] = num;
num++;
}
left++;
//最上面一行
for (int i = left; i <= right; i++)
{
a[top][i] = num;
num++;
}
top++;
}
//输出
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
system("pause");
return 0;
}