Spiral Matrix Leetcode Solution

Spiral Matrix

Given an m x n matrix, return all elements of the matrix in spiral order.

Matrix is  a set of numbers arranged in rows and columns so as to form a rectangular array. The numbers are called the elements, or entries, of the matrix.

 

Walmart CodeHers Coding Challenge 2021-22

Spiral Matrix  Leetcode Solution :

Constraints :

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 10
  • -100 <= matrix[i][j] <= 100

Example 1:

  • Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
  • Output: [1,2,3,4,8,12,11,10,9,5,6,7]

 

Approach :

This approach is not in editorial page but much better than those:
Control the corners as we circle through the whole matrix.

We can store the indices of the corners and using ‘if’ conditions we can traverse in circle. Once we’re back to the element at [0][0], we can shrink the matrix by 1 by manipulating the corner indices.
I might have not done great job in naming the variables in the code. Here are the variables I used to make it easier to understand.

  • r_min -> Index of the first row
  • r_max -> Index of the last row
  • c_min -> Index of the first column
  • c_max -> Index of the last column
  • r and c are the indices of current element to be returned.
spiral matrix leetcode

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Code :

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription