Spiral Matrix

Posted: 31 Oct, 2020
Difficulty: Easy

PROBLEM STATEMENT

Try Problem

You are given a 2-D array 'MATRIX' of dimensions N x M, of integers. You need to return the spiral path of the matrix.

Example Of Spiral Path:

Spiral path of a matrix

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.

The 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 <= 5
1 <= N  <= 10 ^ 2
1 <= M <= 10 ^ 2
-10 ^ 9 <= MATRIX[ i ][ j ] <= 10 ^ 9

Time Limit: 1sec.
Approach 1

For each boundary, we will use the 4 for 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[][], R, C, rows, cols):

  • 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 ‘C’ to ‘cols’, print the elements of the Rth row.
  • Print the last column from top to bottom of the matrix i.e from row ‘R’ to ‘rows’, print the elements of the (cols)th column.
  • Print the last row from right to left of the matrix i.e from column ‘cols’ to ‘C’, print the elements of the (rows)th row.
  • Print the first column from bottom to top of the matrix i.e from row ‘rows’ to ‘R’, print the elements of the Cth column.
  • Call the function recursively with the updated values of boundaries, spiralPrint(matrix, R + 1, C + 1, rows - 1, cols - 1).
Try Problem