Leetcode: Spiral Matrix "54" title description
Given a matrix containing m x n elements (m rows, n columns), return all elements in the matrix in a clockwise spiral order.
Example 1:
Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12]] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
Problem analysis
This problem is simply insane?! the way we use it is a lap of print !
The answer will be all elements in a clockwise order from the first outer layer, then the second outer element, and so on.
We first define four elements,R1,R2,C1,C2, which will frame a range, we print the value on the edge of the range clockwise, and then shrink the box again after each print .
Okay, is that a good question?
1. How many boxes to print?
Times=math.min (long, wide)%2==0? Math.min (long, wide)/2:math.min (long, wide)/2+1;
2. How do you change the horizontal axis of a clockwise print? Have color is the box to print
3, spit Trough this question, simply disgusting.
Java
Class Solution {public list<integer> spiralorder (int[][] matrix) { list<integer> ans = new Arraylist<> (); int m = matrix.length; Line if (m = = 0) return ans; int n = matrix[0].length;//column int c1 = 0; int C2 = n-1; int R1 = 0; int r2 = m-1; int times = Math.min (m,n)%2==0? Math.min (m,n)/2:math.min (m,n)/2+1; for (int i=0;i<times;i++) {for (int c = c1; c <= C2; C + +) Ans.add (Matrix[r1][c]); for (int r = r1 + 1; r <= R2; r++) Ans.add (Matrix[r][c2]); if (R1 < R2 && C1 < C2) {for (int c = c2-1; c > C1; c--) Ans.add (Matrix[r2][c]); for (int r = r2; r > R1; r--) Ans.add (Matrix[r][c1]); } r1++; r2--; c1++; c2--; } return ans; }}
Leetcode: Spiral Matrix "54"