简体   繁体   English

代码适用于较小的输入,但不适用于大型输入。 为什么?

[英]Code works for smaller inputs but it is not working for large inputs. Why?

Given a matrix of m * n elements (m rows, n columns), return all elements of the matrix in spiral order.给定一个由 m * n 个元素(m 行,n 列)组成的矩阵,以螺旋顺序返回矩阵的所有元素。 Why is it working for smaller inputs but not for larger inputs?为什么它适用于较小的输入而不适用于较大的输入? While this same code is working on other systems.而同样的代码也适用于其他系统。 The inputs and the outputs I used are given below.我使用的输入和输出如下。

#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;
}

INPUT:输入:

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

OUTPUT:输出:

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

Check your code:检查您的代码:

for (int i = 0; i < n; i++)
{
    for (int j = 0; j < n; j++)
        cin>>a[i][j];   
}

The second condition should be: j < m第二个条件应该是: j < m

My guess is your code is accessing garbage memory.我的猜测是您的代码正在访问垃圾内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM