Problem
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
1 | |
Example 2:
1 | |
Explanation
-
Similar to (48. Rotate Image ), from the above example2, we can think of four groups:
[1, 2, 3],[4, 8],[12, 11, 10],[9, 5]. Then, we define thetop,right,bottom,left. Whiletop < bottom && left < right, then we loop through each group and add the number tores. -
Out of the loop, it’s either
top > bottom && left > right, then we are done. Else iftop == bottom && left < right, from the above example2, this will be one horizontal row[6, 7]we havn’t added to theres. Else ifleft == right && top < bottom, this will be one vertical column, then we can add those numbers. Finally, we are done.
Solution
1 | |