Given 2D Matrix
1 2 3 4 5 6 7 8 9
Explanation
Step 1: Print the values from first row.
row = 3 & column = 3
1 2 34 5 6 7 8 9
Step 2: Print the last column from top to bottom.
row = 2 & column = 3
4 567 89
Step 3: Print the last row by from right to left.
row = 2 & column = 2
4 57 8
Step 4: Print the first column bottom to top.
row = 1 & column = 2
45
Step 5: Again print the first row. i.e middle row
Print the middle row.
row = 1 & column = 1
5
Java Program
[gist]2c552097029804947d85bbf2a5b4f557[/gist]
Sample Output
1 2 3 6 9 8 7 4 5
Quick Info:
- It is non-regressive function.
- Time Complexity O(n^2)
- Space Complexity O(1)
This is one of the important interview questions 🙂