19.2.8 [LeetCode 54] Spiral Matrix

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;
 7         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 };
View Code

比较容易WA,要处理好特殊情况

猜你喜欢

转载自www.cnblogs.com/yalphait/p/10356435.html