Spiral Matrix LeetCode Solution

Last updated on October 10th, 2024 at 12:29 am

Here, We see Spiral Matrix LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Array

Companies

Google, Microsoft, Uber

Level of Question

Medium

Spiral Matrix LeetCode Solution

Spiral Matrix LeetCode Solution

Problem Statement

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

Example 1:

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

Example 2:

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]

1. Spiral Matrix Leetcode Solution C++

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int>res;
        if(matrix.size() == 0) 
        return res;
        int rs = 0, re = matrix.size() - 1, cs = 0, ce = matrix[0].size() - 1;
        while(rs <= re && cs <= ce)
        {
            for(int i = cs; i <= ce; i++) 
             res.push_back(matrix[rs][i]);
            rs++;
            for(int i = rs; i <= re; i++) 
             res.push_back(matrix[i][ce]);
            ce--;
            for(int i = ce; i >= cs && rs <= re; i--) 
             res.push_back(matrix[re][i]);
            re--;
            for(int i = re; i >= rs && cs <= ce; i--) 
             res.push_back(matrix[i][cs]);
            cs++;
        }
        return res;        
    }
};

2. Spiral Matrix Leetcode Solution Java

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list=new ArrayList<>();
        int left=0,right=matrix[0].length;
        int top=0,bottom=matrix.length;
        while(left<right && top<bottom){
        for(int i=left;i<right;i++){
            list.add(matrix[top][i]);
        }
        top+=1;
        for(int i=top;i<bottom;i++){
            list.add(matrix[i][right-1]);
        }
        right-=1;
         if (!(left<right && top<bottom)){
                break;
            }
        for(int i=right-1;i>left;i--){
            list.add(matrix[bottom-1][i]);
        }
        bottom-=1;
        for(int i=bottom;i>=top;i--){
            list.add(matrix[i][left]);
        }
        left+=1;
    }
        return list;        
    }
}

3. Spiral Matrix Leetcode Solution JavaScript

var spiralOrder = function(matrix) {
  const res = []
  while(matrix.length){
    const first = matrix.shift()
    res.push(...first)
    for(const m of matrix){
      let val = m.pop()
      if(val)
        res.push(val)
        m.reverse()   
    }
    matrix.reverse()
  }
  return res    
};

4. Spiral Matrix Leetcode Solution Python

class Solution(object):
    def spiralOrder(self, matrix):
        return matrix and list(matrix.pop(0)) + self.spiralOrder(zip(*matrix)[::-1])
Scroll to Top