Given an m x n
matrix
, return all elements of the matrix
in spiral order.
![](https://media.geeksforgeeks.org/wp-content/uploads/20200421034622/untitled1810.png)
Input:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
![](https://assets.leetcode.com/uploads/2020/11/13/spiral1.jpg)
def printSpiralOrder(mat): # base case if not mat or not len(mat): return top = left = 0 bottom = len(mat) - 1 right = len(mat[0]) - 1 while True: if left > right: break # print top row for i in range(left, right + 1): print(mat[top][i], end=' ') top = top + 1 if top > bottom: break # print right column for i in range(top, bottom + 1): print(mat[i][right], end=' ') right = right - 1 if left > right: break # print bottom row for i in range(right, left - 1, -1): print(mat[bottom][i], end=' ') bottom = bottom - 1 if top > bottom: break # print left column for i in range(bottom, top - 1, -1): print(mat[i][left], end=' ') left = left + 1 #Driver Matrx = [] ''' Matrx = [ [1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9] ] ''' while True: arr=list(map(str,input().split(" "))) if arr != ['']: Matrx.append(list(map(int,arr))) else: break printSpiralOrder(Matrx)
INPUT_1:
1 2 3 4 5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
INPUT_2:
100 200 300
400 500 600
700 800 900
OUTPUT:
100 200 300 600 900 800 700 400 500
INPUT_3:
5 6 7
10 9 8
OUTPUT:
5 6 7 8 9 10
ILLUSTRATION
![](http://www.fcukthecode.com/wp-content/uploads/2022/01/Screenshot-from-2022-01-13-21-06-20.png)
Morae Q!
- Find the length of the array’s longest increasing sub-sequence.
- Arrange numbers in a circle so that any two neighbouring numbers differ by 1.
- Find partial names and count the total numbers.
- Find the minimized sum of non-deleted elements of the array after the end of the game.
- Find the maximum number of good sleeping times optimally.
- Sort the elements of the array in the order in which they are required.
- Find the minimum number of flats, monkey needs to visit to catch ninjas.
- Convert the square matrix to matrix in Z form.
- Shift the K elements of each row to right of the matrix.
- Find maximum possible number of students in a balanced team with skills.
- Find the Maximum number of pairs of points you can match with each other.
- Calculate the number of non-empty good subarrays of given array.
- Transform the binary string A into the string B using finite operations.
- Find the number of potion must the character take to jump the hurdles.
- Count the total number of vowels and consonants.
- Return all elements of the matrix in spiral order.
- Return all palindromic paths of the matrix.
- Write the code to change the display in reverse order using pointer.
- Find the number of days the expedition can last.
- Find the minimum size of the sub-segment to make the array pairwise distinct.