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(vectorint>>& matrix) {
 4         vector<int> res;
 5         int m = matrix.size();
 6         if (m == 0)
 7             return res;
 8         int n = matrix[0].size();
 9         int cnt = 0;
10         res.resize(m * n);
11         int start_row = 0, start_col = 0, end_row = m - 1, end_col = n - 1;
12         while (cnt < m * n) {
13             for (int j = start_col; cnt < m * n && j <= end_col; j++) {
14                 res[cnt++] = matrix[start_row][j];
15             }
16             for (int i = start_row + 1; cnt < m * n && i <= end_row; i++) {
17                 res[cnt++] = matrix[i][end_col];
18             }
19             for (int j = end_col - 1; cnt < m * n && j >= start_col; j--) {
20                 res[cnt++] = matrix[end_row][j];
21             }
22             for (int i = end_row - 1; cnt < m * n && i > start_row; i--) {
23                 res[cnt++] = matrix[i][start_col];
24             }
25             start_row++;
26             start_col++;
27             end_row--;
28             end_col--;
29         }
30         return res;
31     }
32 };

 

你可能感兴趣的:(leetcode 54. Spiral Matrix)