19.2.8 [LeetCode 54] Spiral Matrix
阿新 • • 發佈:2019-02-08
display event || 圖片 tor example element amp pla
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in 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]
題意
順時針螺旋輸出數組
題解
1 class Solution { 2 public: 3 vector<int> spiralOrder(vector<vector<int>>& matrix) { 4 if (matrix.empty())return vector<int>(); 5 int line=matrix.size(),row=matrix[0].size(),n = row*line; 6 vector<int>ans;View Code7 int s = -1, e = row, ss = -1, ee = line; 8 for (int i = 0; i < (line + 1) / 2; i++) { 9 s++, e--, ss++, ee--; 10 if (e < s || ee < ss)break; 11 for (int j = s; j <= e; j++) 12 ans.push_back(matrix[i][j]); 13 for(int j = ss+1; j <= ee; j++) 14 ans.push_back(matrix[j][e]); 15 if (ss != ee) { 16 for (int j = e - 1; j >= s; j--) 17 ans.push_back(matrix[ee][j]); 18 } 19 if (s != e) { 20 for (int j = ee - 1; j > ss; j--) 21 ans.push_back(matrix[j][s]); 22 } 23 } 24 return ans; 25 } 26 };
比較容易WA,要處理好特殊情況
19.2.8 [LeetCode 54] Spiral Matrix