Spiral Print of An Array Matrix

41 views Asked by At
`#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector<vector<int>> arr{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int number = 0;
    int rows = 0;
    int column = 0;
    bool isgoingupdown = false;
    int numrows = arr.size();
    int numcolumn = arr[1].size();
    bool isgoingrightleft = true;
    while (number < numrows * numcolumn + 1)
    {
        if (isgoingrightleft)
        {
            if (column == numcolumn - 1)
            {
                cout << arr[rows][column];
                rows = rows + 1;
                isgoingupdown = true;
                isgoingrightleft = false;
                numrows--;
                number++;
            }
            else
            {
                cout << arr[rows][column];
                column++;
                number++;
            }
        }
        if (isgoingupdown && column == numcolumn - 1)
        {
            if (rows == numrows)
            {
                cout << arr[rows][column];
                isgoingrightleft = true;
                isgoingupdown = false;
                column--;
                number++;
                numcolumn--;
            }
            else
            {
                cout << arr[rows][column];
                rows++;
                number++;
            }
        }

        if (isgoingrightleft && rows == numrows)
        {
            if (column== arr[0].size()-numcolumn-1)
            {
                cout<<arr[rows][column];
                number++;
                numrows--;
                isgoingupdown = true;
                isgoingrightleft = false;
                rows--;
            }
            else
            {
                cout<<arr[rows][column];
                column--;
                
                number++;
               
                
            }
        }
        if (isgoingupdown && column == arr[1].size() - numcolumn - 1)
        {
            if (rows == arr.size() - 1 - numrows)
            {
                cout << arr[rows][column];
                number++;
                isgoingrightleft = true;
                isgoingupdown = false;
                numcolumn--;
                column++;
            }

            else
            {
                cout << arr[rows][column];
                rows--;
                number++;
            }
        }
    }

    return 0;
}

why does this code produce only 123698 and not 745?

I was expecting 123698745 instead of 123698 and i tried several value of column and also used GPT but could not land into a solution. This is the code that i have written that prints the matrix in the spiral pattern but i am unable to print the solution completely after 8 in the complete solution. I have tried to do the solution in O(n) complexity.

0

There are 0 answers