【问题标题】:Spiral matrix, i am getting extra elements while printing spiral matrix order. Don't know why?螺旋矩阵,我在打印螺旋矩阵顺序时得到了额外的元素。不知道为什么?
【发布时间】:2022-01-18 11:54:55
【问题描述】:
// printing in spiral order matrix 
#include<iostream>
using namespace std;

int main(){
    int n,m;
    cin>>n>>m;
    int arr[n][m];
    for(int i=0; i<n; i++){
        for(int j=0; j<m; j++){
            cin>>arr[i][j];
        }
    }
    // print
    for(int i=0; i<n; i++){
        for(int j=0; j<m; j++){
            cout<<arr[i][j]<<" ";
        }
        cout<<endl;
    }
    // spiral print
    int row_start=0,row_end=n-1,col_start=0,col_end=m-1;
    while(row_start<=row_end && col_start<=col_end){
        for(int j=col_start; j<=col_end; j++){
            cout<<arr[row_start][j]<<" ";
        }
        row_start++;
        for(int i=row_start; i<=row_end; i++){
            cout<<arr[i][col_end]<<" ";
        }
        col_end--;
        for(int j=col_end; j>=col_start; j--){
            cout<<arr[row_end][j]<<" ";
        }
        row_end--;
        for(int i=row_end; i>=row_start; i--){
            cout<<arr[i][col_start]<<" ";
        }
        col_start++;
    }
    return 0;
}

我的输出是:

PS C:\Users\anmol\Desktop\c++projectwork> ./a
3 4 
1 2 3 4 5 6 7 8 9 0 1 2
1 2 3 4 
5 6 7 8 
9 0 1 2
1 2 3 4 8 2 1 0 9 5 6 7 6

最后我得到一个额外的“6”。 这不是必需的,但是只有当矩阵是矩形时才会出现这种类型的问题。 但代码适用于方阵。 请告诉我哪里出错了..

【问题讨论】:

  • 您是否使用调试器运行过代码以查明问题所在?
  • int arr[n][m]; 不是标准 C++。避免使用非标准结构。
  • 你试过使用调试器吗?我建议尝试使用 1 行 5 列的矩阵。
  • 回避这个问题的一个简单方法是计算你输出的元素数量。一旦你到达n*m,就停下来。

标签: c++ spiral


【解决方案1】:

假设你有一个下面的矩阵。让我们在下面的示例中运行您的代码。

1 2 3 4

5 6 7 8

9 10 11 12

试运行

第一个 for 循环:打印 1 2 3 4 row_start=1,row_end=2,col_start=0,col_end=3

第二个 for 循环:打印 8 12 row_start=1,row_end=2,col_start=0,col_end=2

第三个 for 循环:打印 11 10 9 row_start=1,row_end=1,col_start=0,col_end=2

第 4 个 for 循环:打印 5 个 row_start=1,row_end=1,col_start=1,col_end=2

while 循环的所有条件都为真 while 循环的第二次迭代:

第一个 for 循环:打印 6 7 row_start=2,row_end=1,col_start=1,col_end=2

第二个 for 循环:不会做任何事情 row_start=2,row_end=1,col_start=1,col_end=1

第三个 for 循环:打印 6

你发现问题了吗?

只有在以下情况下才应该运行第三个 for 循环

"row_start

同样你应该检查

"col_start

在运行第四个循环之前

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多