Spiral matrix algorithm

The Spiral Matrix problem takes a 2-Dimensional array of N-rows and M-columns as an input, and prints the elements of this matrix in spiral order.

The spiral begins at the top left corner of the input matrix, and prints the elements it encounters, while looping towards the center of this matrix, in a clockwise manner. ​

How does the spiral matrix algorithm work?

1 of 17
  • First, four variables containing the indices for the corner points of the array are initialized.
  • The algorithm starts from the top left corner of the array, and traverses the first row from left to right. Once it traverses the whole row it does not need to revisit it, thus, it increments the top corner index.
  • Once complete, it traverses the rightmost column top to bottom. Again, once this completes, there is no need to revisit the rightmost column, thus, it decrements the right corner index.
  • Next, the algorithm traverses the bottommost row and decrements the bottom corner index afterward.
  • Lastly, the algorithm traverses the leftmost column, incrementing the left corner index once it’s done.

This continues until the left index is greater than the right index, and the top index is greater than the bottom index.

Implementation

The following code implements the spiral matrix algorithm in C++, Python, and Java:

#include <iostream>
using namespace std;
// Change values of M and N to change the
// dimensions of the input matrix.
#define N 4
#define M 4
void spiralMatrixPrint(int rows, int cols, int arr[N][M]) {
// Defining the boundaries of the matrix.
int top = 0, bottom = rows - 1, left = 0, right = cols - 1;
// Defining the direction in which the array is to be traversed.
int dir = 1;
while (top <= bottom && left <= right) {
if (dir == 1) { // moving left->right
for (int i = left; i <= right; ++i) {
cout<<arr[top][i] << " ";
}
// Since we have traversed the whole first
// row, move down to the next row.
++top;
dir = 2;
}
else if (dir == 2) { // moving top->bottom
for (int i = top; i <= bottom; ++i) {
cout<<arr[i][right] << " ";
}
// Since we have traversed the whole last
// column, move left to the previous column.
--right;
dir = 3;
}
else if (dir == 3) { // moving right->left
for (int i = right; i >= left; --i) {
cout<<arr[bottom][i] << " ";
}
// Since we have traversed the whole last
// row, move up to the previous row.
--bottom;
dir = 4;
}
else if (dir == 4) { // moving bottom->up
for (int i = bottom; i >= top; --i) {
cout<< arr[i][left] << " ";
}
// Since we have traversed the whole first
// col, move right to the next column.
++left;
dir = 1;
}
}
}
int main() {
// Driver code
int mat[N][M] = { { 1, 2, 3, 4 },
{ 12, 13, 14, 5 },
{ 11, 16, 15, 6 },
{ 10, 9, 8, 7 } };
spiralMatrixPrint(N, M, mat);
return 0;
}

Copyright ©2024 Educative, Inc. All rights reserved