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.
Related Posts:
- Find Pivot Index (Leet Code-724)
- Isomorphic Strings
- Two Sum IV - Input is a BST (Leet Code-653)
- Search in a Binary Search Tree (Leet Code-700)
- Invert Binary Tree (Leet Code-266)
- Symmetric Tree (Leet Code-101)
- Maximum Depth of Binary Tree (Leet Code-104)
- Binary Tree Postorder Traversal (Leet Code-145)
- Binary Tree Inorder Traversal (Leet Code - 94)
- Binary Tree Pre-Order Traversal
- Binary Tree Level Order Traversal (Leet Code-102)
- Valid Parentheses (Leet Code-20)
- Remove Duplicates from Sorted List (Leet Code-83)
- Reverse Linked List (Leet code -206)
- Remove Linked List Elements (Leet Code-203)
- Merge Two Sorted Lists (Leet code-21)
- Ransom Note (Leet code-383)
- First Unique Character in a String (Leet code-387)
- Valid Sudoku (Leet Code-36)
- Search a 2D Matrix (Leet Code-74)
- Linked List Cycle (Leet Code-141)
- Pascal's Triangle (Leet Code - 118)
- Reshape the Matrix (Leet Code-566)
- Best Time to Buy and Sell Stock (Leet code-121)
- The Intersection of Two Arrays II (Leet Code)
- Binary Search - Leet Code
- Two Sum - Leet Code
- Kadane's Algorithm /Largest Sum Contiguous Subarray
- Subarray with given sum(Non-negative Numbers)
- Check for Binary Search Tree