Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I iterate through a two-dimensional array in a snail mode, with a single cycle?

Given a two dimensional array, I would like to iterate through it in a snail mode and print out the elements using one single cycle.

For example if the given array is:

10 11 12 13 14
15 16 17 18 19
20 21 22 23 24
25 26 27 28 29
30 31 32 33 34

The program should print out:

10 15 20 25 30 31 32 33 34 29 24 19 14 13 12 11 16 21 26 27 28 23 18 17 22

So starting from the upper-left corner and arriving to the center of the array.

like image 685
Róbert Nagy Avatar asked Sep 01 '25 22:09

Róbert Nagy


1 Answers

Here is the solution with one for loop:

It works only when the matrix is: n >= m

#include <iostream>

using namespace std;

int main()
{
//    int arr[4][3] = {{0, 9, 8} , {1, 10 , 7} , {2, 11, 6} , {3, 4, 5}};
//    int n = 4, m = 3;

    int arr[4][4] = {{0, 11, 10, 9} , {1, 12, 15, 8} , {2, 13, 14, 7} , {3, 4, 5, 6}};
    int n = 4, m = 4;

    int row = 0, col = 0, turn = 0;
    bool isTop = true;

    for(int nrElem = 0; nrElem <= (n*m); nrElem++)
    {
        //This part make the left, bottom, right part ( U form )
        if((row < n-1-turn) && (col != m-1) && (isTop == true))
        {
            cout << " " << arr[row][col];
            row++;
        } else {
            if((row == n-1-turn) && (col < m-1-turn))
            {
                cout << " " << arr[row][col];
                col++;
            } else {
                if((col == m-1-turn) && (row > 0))
                {
                    cout << " " << arr[row][col];
                    row--;
                } else {
                    isTop = false;
                }
            }
        }
        //

        //And this do the top backward parsing
        if((col > 0) && (isTop == false))
        {
            cout << " " << arr[row][col];
            col--;
        } else {
            if (isTop == false)
            {
                isTop = true;
                turn++;
                row += turn;
                col += turn;
            }
        }
    }

    cout << endl;
    return 0;
}
like image 67
Orbán Hunor Avatar answered Sep 03 '25 18:09

Orbán Hunor