Print a matrix in spiral order

Given a nxm matrix , print the matrix in spiral order.

Test Case

Example 1

Sample Input:

[1 2 3 4 5 6]
[16 17 18 19 6]
[15 24 25 20 7]
[14 23 22 21 8]
[13 12 11 10 9]

Expected Output: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

Solution

To solve this problem, we will define 4 variables

  1. left: This is the index of the leftmost column that needs to be printed. Its initial value will be 0
  2. right: This is the index of the rightmost column that needs to be printed. Its initial value will be m-1, where m is the number of columns in the matrix.
  3. top. This is the index of the topmost row that needs to be printed. Its initial value will be 0.
  4. bottom: This is the index of the bottommost row which needs to be printed. Its initial value will be n-1, where n is the number of rows in the matrix.

Initially, the values of left, right, top and bottom would be as shown in the diagram below:

After that we will start by writing 4 loops for printing the topmost row, rightmost column, bottom-most row and leftmost column respectively.

After every for loop we will change the value of the corresponding variable (left/right/top/bottom). As soon as we see that there are no more elements left to print, we will exit the loop

See the below GIF to understand it better

Implementation

Implementation of the above solution to print matrix in spiral order is given below:

#include <bits/stdc++.h>
using namespace std;

int main() {
    vector<vector<int>> vec = { { 1, 2, 3, 4, 5 }, { 16, 17, 18, 19, 6 }, {15, 24, 25, 20, 7 }, { 14, 23, 22, 21, 8}, {13, 12, 11, 10, 9 }};

    // The boundaries for the current iteration
    int top = 0, bottom = vec.size() - 1, left = 0, right = vec[0].size() - 1;

    while (top <= bottom && left <= right) {

        // Print Top Row of the matrix
        for(int i = left; i <= right; i++) {
            cout << vec[top][i] << " ";
        }
        top++;

        // Print right side
        for(int i = top; i <= bottom; i++) {
            cout << vec[i][right] << " ";
        }
        right--;

        // Print Bottom Row
        for(int i = right; i >= left; i--) {
            cout << vec[bottom][i] << " ";
        }

        bottom--;

        // Print left row
        for(int i = bottom; i >= top; i--) {
            cout << vec[i][left] << " ";
        }
        left++;
    }

    cout << "\n";
}
Scroll to Top