【发布时间】:2021-09-17 21:21:30
【问题描述】:
给定一个 m * n 个元素(m 行,n 列)的矩阵,以螺旋顺序返回矩阵的所有元素。为什么它适用于较小的输入但不适用于较大的输入?虽然相同的代码在其他系统上工作。我使用的输入和输出如下所示。
#include<iostream>
using namespace std;
int main(){
int n,m;
cin>>n>>m;
int a[n][m];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
cin>>a[i][j];
}
// spiral order print
int row_start = 0, row_end = n-1, column_start = 0, column_end = m-1;
while (row_start <= row_end && column_start <= column_end)
{
//for row start
for (int col = column_start; col <= column_end; col++)
{
cout<<a[row_start][col]<<" ";
}
row_start++;
//for column end
for (int row = row_start; row <= row_end; row++)
{
cout<<a[row][column_end]<<" ";
}
column_end--;
//for row end
for (int col = column_end; col >= column_start; col--)
{
cout<<a[row_end][col]<<" ";
}
row_end--;
//for column start
for (int row = row_end; row >= row_start; row--)
{
cout<<a[row][column_start]<<" ";
}
column_start++;
}
return 0;
}
输入:
5 6
1 5 7 9 10 11
6 10 12 13 20 21
9 25 29 30 32 41
15 55 59 63 68 70
40 70 79 81 95 105
输出:
1 5 7 9 10 1878030368 -1 -1 6422096 4200108 40 70 68 63 59 30 20 11 6 10 12 13 29 55 15 41 32 21 9 25 9
【问题讨论】:
-
int a[n][m];不是标准 C++。 Why aren't variable-length arrays part of the C++ standard?。它是一个非标准的编译器扩展。如果你想知道它是如何工作的或不工作的,你必须阅读你的编译器手册。无论如何,您不能在堆栈上分配任意数量的数据。更好地将std::vector用于动态数组 -
for (int j = 0; j < n; j++)->for (int j = 0; j < m; j++)。不过可能还有其他问题 -
数组
int a[n][m]的维度应该在编译时就知道了。如果要使用在运行时公开的数组大小,可以使用动态数组(用new声明的数组)或std::vector。我建议使用std::vector。 -
如果 m 和 n 足够大,
int a[n][m];很容易溢出堆栈。
标签: c++ arrays multidimensional-array spiral