Problem of the day
You are given a 2D matrix ‘MATRIX’ of ‘N’*’M’ dimension. You have to return the spiral traversal of the matrix.
Example:
Input:
MATRIX = [ [1, 3, 5, 7], [10, 11, 16, 20], [23, 30, 34, 60] ]
Output:
1 3 5 7 20 60 34 30 23 10 11 16
Explanation: Starting from the element in the first row and the first column, traverse from left to right (1 3 5 7), then top to bottom (20 60), then right to left (34 30 23), then bottom to up (10) and then left to right (11 16).
The first line of the input will contain two integers denoting the dimensions of the matrix ‘N’ and ‘M’.
The following 'N' lines contain ‘M’ integers each.
Output Format:-
Output is printed on a separate line.
Note:-
You don’t need to print anything. Just implement the given function.
1 <= N, M <= 10^5
1 <= MATRIX [ i ] [ j ] <= 10^9
The sum of N*M over all test cases is less than 2*10^5.
Time Limit: 1 sec
3 3
1 3 7
10 12 15
19 20 21
1 3 7 15 21 20 19 10 12
Input:
MATRIX = [ [1, 3, 7], [10, 12, 15], [19, 20, 21] ],
Output:
1 3 7 15 21 20 19 10 12
Explanation: Starting from the element in the first row and the first column, traverse from left to right (1 3 7), then top to bottom (15 21), then right to the left (20 19), then bottom to up (10) and then left to right (12).
4 4
1 5 9 13
14 15 16 17
19 20 21 50
59 60 71 80
1 5 9 13 17 50 80 71 60 59 19 14 15 16 21 20
Stimulate the problem statement.
Approach:
Algorithm:
Function [int] spiralMatrix([int][int] MATRIX):
O( N*M ), Where ‘N’ and ‘M’ are the given matrix ‘MATRIX’ dimensions.
We are traversing all the N*M elements of the matrix. Hence, the overall time complexity will be O( N*M ).
O( 1 ).
We are taking O( 1 ) extra space for variables. Hence, the overall space complexity will be O( 1 ).