题目描述
输入一个矩阵的层数,生成如下矩阵并进行输出。例如:输入3,则输出
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
输入描述
一行包含一个整数 n,表示矩阵的层数。
输出描述
一个n层的矩阵
样例1
输入
3
输出
3 3 3 3 3
3 2 2 2 3
3 2 1 2 3
3 2 2 2 3
3 3 3 3 3
提示
1 <= n <= 100
#include
using namespace std;
int main()
{
int a[104][104]={},n;
cin>>n;
for(int i=1;i<=n;i++)
{
for(int j=2*n-1;j>=1;j--)
{
a[i][j]=i;
a[2*n-i][j]=i;
a[j][i]=i;
a[j][2*n-i]=i;
}
}
for(int i=2*n-1;i>=1;i--)
{
for(int j=2*n-1;j>=1;j--)
{
cout<" ";
}
cout<return 0;
}
将代码中的一个循环改成如下形式:
for(int i=1;i<=n;i++)
{
for(int j=2*n-i;j>=i;j--)
{
a[i][j]=n-i+1;
a[2*n-i][j]=n-i+1;
a[j][i]=n-i+1;
a[j][2*n-i]=n-i+1;
}
}
“Devil组”引证GPT后的撰写:
在双重循环中,使用了固定的循环次数 $2n-1$ 来生成矩阵,但是没有正确计算矩阵中每个元素应该填充的值。因此,生成的矩阵并不符合要求。
以下是一种可以正确生成矩阵的代码实现:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
// 初始化矩阵
int matrix[201][201];
int startRow = 0, endRow = 2 * n - 2, startCol = 0, endCol = 2 * n - 2;
int curValue = n;
while (startRow <= endRow && startCol <= endCol) {
// 填充上方行
for (int col = startCol; col <= endCol; col++) {
matrix[startRow][col] = curValue;
}
startRow++;
// 填充右侧列
for (int row = startRow; row <= endRow; row++) {
matrix[row][endCol] = curValue;
}
endCol--;
// 填充下方行
for (int col = endCol; col >= startCol; col--) {
matrix[endRow][col] = curValue;
}
endRow--;
// 填充左侧列
for (int row = endRow; row >= startRow; row--) {
matrix[row][startCol] = curValue;
}
startCol++;
// 下一层
curValue--;
}
// 输出矩阵
for (int i = 0; i < 2 * n - 1; i++) {
for (int j = 0; j < 2 * n - 1; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
}
输出: