Array ( [0] => [1] => questions [2] => Arrays [3] => Spiral-Matrix ) Arrays | Spiral Matrix | THE INQUISITIVE





Spiral Matrix

LEVEL:Beginner

Description

Given a 2D array of integers of n*n shape. You have to print the elements in spiral matrix.

Input Format

First line contains the size of the dimension n. Next n line contains the m integers separated by the spaces.

Output Format

Print the elements in spiral form.


Example 1:

Input
3
1 2 3
4 5 6 
7 8 9
Output
1 2 3 6 9 8 7 4 5	
Example 2:

Input
4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output
1 2 3 4 8 12 16 15
14 13 9 5 6 7 11 10
Example 3:

Input
5
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
Output
1 2 3 4 5 10 15 20 25 24 23 22 21 16 
11 6 7 8 9 14 19 18 17 12 

oops

Login to see Discussion




Approach

Approach1:

Step-i) Print the top row, Print the elements of kth row from column index l to n.
Step-ii)increase the value of k.
Step-iii) Print the right column, Print the last column or n-1th column from row index k to m
Step-iv) Decrease the value of n.
Step-v) Print the bottom row, if k > m, then print the elements of m-1th row from column n-1 to l. Step-vi) Decrease the value of m.
Step-vii) Print the left column, if l < n, then print the elements of lth column from m-1th row to k. Step-viii) Increase the value of l.

Time Complexity: O(n^2)
Space Complexity: O(n^2)


Note :

Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.

oops

Login to see Solution