题目:
输入两个整数 n 和 m,输出一个 n行 m列的矩阵,将数字 1到 n×m 按照回字蛇形填充至矩阵中。
输入格式
输入共一行,包含两个整数 n 和 m。
输出格式
输出满足要求的矩阵。
矩阵占 n 行,每行包含 m 个空格隔开的整数。
数据范围
1≤n,m≤100
输入样例:
3 3
输出样例:
1 2 3
8 9 4
7 6 5
思路:
用 left 指向待输出部分的最左侧,right 指向待输出部分的最右侧,top 指向待输出部分的最上侧,bottom 指向待输出部分的最下侧。
初始化:
left=0;right=m-1;top=0;bottom=n-1.
循环指向:
1. 从左到右构造最上侧的一行,待输出部分的最上侧下移,然后top+1。
for(int i = left; i <= right && top <= bottom; i++)//构造最上面一行
{
a[top][i] = k++;
}
top++;
2. 从上到下构造最右侧的一列,待输出部分的最右侧左移,然后right-1。
for(int i = top; i <= bottom && left <= right; i++)//构造最右侧一列
{
a[i][right] = k++;
}
right--;
3. 从右到左构造最下方的一行,待输出部分的最下侧上移,然后bottom-1。
for(int i = right; i >= left && top <= bottom; i--)//构造最下面一行
{
a[bottom][i] = k++;
}
bottom--;
4. 从下到上构造最右侧的一列。待输出部分的最左侧右移。然后left+1。
for(int i = bottom; i >= top && left <= right; i--)//构造最左侧一列
{
a[i][left] = k++;
}
left++;
完整代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 110;
int a[N][N];
int main()
{
int n,m;
cin >> n >> m;//n行m列
int left = 0, right = m - 1;
int top = 0, bottom = n - 1;
int k = 1;
while(left <= right || top <= bottom)
{
for(int i = left; i <= right && top <= bottom; i++)//构造最上面一行
{
a[top][i] = k++;
}
top++;
for(int i = top; i <= bottom && left <= right; i++)//构造最右侧一列
{
a[i][right] = k++;
}
right--;
for(int i = right; i >= left && top <= bottom; i--)//构造最下面一行
{
a[bottom][i] = k++;
}
bottom--;
for(int i = bottom; i >= top && left <= right; i--)//构造最左侧一列
{
a[i][left] = k++;
}
left++;
}
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++) cout<< a[i][j] << " ";
cout << endl;
}
return 0;
}