c++spiral

Spiral matrix, i am getting extra elements while printing spiral matrix order. Don't know why?


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

My output is:

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

I am getting an extra '6' at the end. which is not required however this type of problem only come when matrix is rectangular. But code works fine for square matrix. Please tell me where i went wrong..


Solution

  • Suppose you have a below matrix. Let's dry run your code on below example.

    1 2 3 4

    5 6 7 8

    9 10 11 12

    Dry Run

    1st for loop: prints 1 2 3 4 row_start=1,row_end=2,col_start=0,col_end=3

    2nd for loop: prints 8 12 row_start=1,row_end=2,col_start=0,col_end=2

    3rd for loop: prints 11 10 9 row_start=1,row_end=1,col_start=0,col_end=2

    4th for loop: prints 5 row_start=1,row_end=1,col_start=1,col_end=2

    All condition of while loop are true 2nd Iteration of while loop:

    1st for loop: prints 6 7 row_start=2,row_end=1,col_start=1,col_end=2

    2nd for loop: won't do anything row_start=2,row_end=1,col_start=1,col_end=1

    3rd for loop: prints 6

    DO you see the problem?

    you should run 3rd for loop only if

    "row_start < row_end"

    similarly you should check for

    "col_start<col_end"

    before running the 4th loop