Spiral Matrix

Spiral Matrix Problem Solution

This article is another part of a series on leet code problem solutions and Geeks For Geeks problem Solutions and it provides a solution to the leet code problem number 226. This is a Leet code problem named Spiral Matrix and a GFG problem called Spirally traversing a matrix. We will solve it using python and it is the best space and time-optimized solution. 

Question of Spiral Matrix

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

Draw the spiral’s course. Every time the path would venture outside of its boundaries or enter a cell that has already been visited, we know that the path should turn clockwise.

We don’t need to read input or print anything. Complete the function  that takes matrix, r and c as input parameters and returns a list of integers denoting the spiral traversal of matrix

Example

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]

Constraints

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

Approach to solve Spiral Matrix

To solve this problem we run the while loop and in each iteration, we first traverse left to right, and then we will traverse top to bottom and after that, we traveres right to left and at last bottom to top. We repeat this process until we traverse the whole matrix.

Python Code for Spiral Matrix

Leet Code Solution

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        res = []
        left, right = 0, len(matrix[0])
        top, bottom =0, len(matrix)
        while left< right and top< bottom:
            #left to right
            for i in range(left,right):
                res.append(matrix[top][i])
            top +=1
            #top to bottom
            for i in range(top,bottom):
                res.append(matrix[i][right-1])
            right -= 1

            #right to left
            for i in range(right-1,left-1,-1):
                res.append(matrix[bottom-1][i])
            bottom -=1
            #bottom to top last time
            for i in range(bottom-1,top -1,-1):
                res.append(matrix[i][left])
            left +=1
            
         
        return res[:len(matrix)*len(matrix[0])]

Geeks For Geeks Code Solution

class Solution:
    
    #Function to return a list of integers denoting spiral traversal of matrix.
    def spirallyTraverse(self,matrix, r, c): 
        # code here 
        res = []
        left, right = 0, len(matrix[0])
        top, bottom =0, len(matrix)
        while left< right and top< bottom:
            #left to right
            for i in range(left,right):
                res.append(matrix[top][i])
            top +=1
            #top to bottom
            for i in range(top,bottom):
                res.append(matrix[i][right-1])
            right -= 1

            #right to left
            for i in range(right-1,left-1,-1):
                res.append(matrix[bottom-1][i])
            bottom -=1
            #bottom to top last time
            for i in range(bottom-1,top -1,-1):
                res.append(matrix[i][left])
            left +=1
            
         
        return res[:len(matrix)*len(matrix[0])]


#{ 
 # Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        r,c = map(int, input().strip().split())
        values = list(map(int, input().strip().split()))
        k = 0
        matrix =[]
        for i in range(r):
            row=[]
            for j in range(c):
                row.append(values[k])
                k+=1
            matrix.append(row)
        obj = Solution()
        ans = obj.spirallyTraverse(matrix,r,c)
        for i in ans:
            print(i,end=" ")
        print()

# } Driver Code Ends

Complexity Analysis

Time Complexity: O(n)

n is the number of nodes in the binary tree. 

Space Complexity: O(n)

 n is the number of nodes in the binary tree.

So here is the end of the post. If you find any issues or any questions then write a comment. Share with your friends.

Tags: No tags

Leave A Comment

Your email address will not be published. Required fields are marked *