Last Updated: 19 Dec, 2020

Spiral Matrix

Easy
Asked in companies
CultfitOracleGoldman Sachs

Problem statement

You are given a N x M matrix of integers, print the spiral path of the matrix.

For example:

Spiral Path

Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases follow.

The first line of each test case contains two single space-separated integers N and M, denoting the number of rows and columns respectively.

The next 'N' lines, each contains 'M' single space-separated integers representing the elements in a row of the matrix.
Output format :
For each test case/query, print the spiral path of the given matrix.

Output for every test case will be printed in a separate line.
Note:
 You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 10
1 <= N <= 100
1 <= M <= 100
-10^9 <= data <= 10^9

where ‘T’ is the number of test cases,  ‘N’ and ‘M’ are the numbers of rows and columns respectively and ‘data’ is the value of the elements of the matrix.

Approaches

01 Approach

For each boundary, we will use the 4 loops. Now the problem is reduced to print the remaining submatrix which is handled with the help of recursion. Keep track of new dimensions(rows and columns) of the current submatrix which are passed with the help of parameters in each recursion call.
 

Algorithm:
 

spiralPrint(matrix[][], startingRow, startingCol, endingRow, endingCol):

  • Check for base cases, i.e. if outside the boundary of the matrix, then return.
  • Print the first row from left to right of the matrix i.e from column ‘startingCol’ to ‘endingCol’, print the elements of the ‘startingRow’ row.
  • Print the last column from top to bottom of the matrix i.e from row ‘startingRow+1’ to ‘endingRow’, print the elements of the ‘endingCol’ column.
  • Print the last row from right to left of the matrix i.e from column ‘endingCol-1’ to ‘startingCol’, print the elements of the ‘endingRow’ row.
  • Print the first column from bottom to top of the matrix i.e from row ‘endingRow-1’ to ‘startingRow+1’, print the elements of the Cth column.
  • Call the function recursively with the updated values of boundaries, spiralPrint(matrix, startingRow+1, startingCol+1, endingRow-1, endingCol-1)

02 Approach

The idea is to traverse the matrix using loops where each loop will be used for a specific direction to print all the elements in the clockwise order layer by layer. Every loop traverses the matrix in a single direction. The first loop traverses the matrix from left to right, the second loop traverses the matrix from top to bottom, the third traverses the matrix from the right to left, and the fourth traverses the matrix from bottom to up. After completing the traversal using 4 loops one time, repeat it again for the remaining submatrix. To traverse using these loops we will initialize 4 variables to keep the boundaries of the submatrix as explained below.
 

Algorithm:
 

spiralPrint(matrix[][], rows, cols):

  • Initialize two variables R, C with 0 to denote the lowest boundary for row and column of the submatrix remaining. Also, rows and cols denote the maximum boundary for the submatrix remaining.
  • While(R < rows and C < cols) :
    • Print the first row from left to right of the remaining submatrix i.e from column C to ‘cols’, print the elements of the Rth row. Increment R by 1.
    • Print the last column from top to bottom of the remaining submatrix i.e from row R to ‘rows’, print the elements of the (cols)th column. Decrement ‘cols’ by 1.
    • Print the last row from right to left of the remaining submatrix i.e from column ‘cols’ to C, print the elements of the (rows)th row. Decrement ‘rows’ by 1.
    • Print the first column from bottom to top of the remaining submatrix i.e from row ‘rows’ to R, print the elements of the Cth column. Increment C by 1.
  • Update the value of i to (row - 1) and j to (column - 1).

 

03 Approach

In previous approaches, we are using four loops to print the boundary of a matrix.

  • From left to right: row is constant, increasing column by 1.
  • From top to bottom: column is constant, increasing row by 1.
  • From right to left: row is constant, decreasing column by 1.
  • From bottom to top: column is constant, decreasing row by 1.

For this, we will take four operations { (0,1), (1,0), (0,-1), (-1,0) } which will change row or column. We will iterate on these operations cyclically, i.e, operation 1 is next to operation 4.
 

We will make a 2D array to store the visited cells. 
 

Take two variables R (current row) and C (current column) and initialize them with 0. Let’s take another variable ‘cur’ which denotes the type operation to be performed, initially it will be 0.
 

Algorithm:
 

Run a loop from 1 to total number of elements in the matrix:

  • Push  the current cell element in the spiral path and mark the current cell to be visited.
  • Perform the current operation on the cell.
  • If we move out of the boundary or reach a cell which is already visited, then we change the operation ‘cur’ to the next value and perform this operation on the current cell.
  • Else, repeat the same process.