码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 54. Spiral Matrix

时间:2019-09-16 23:48:01      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:pre   spi   output   art   amp   resize   input   style   inpu   

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         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

标签:pre   spi   output   art   amp   resize   input   style   inpu   

原文地址:https://www.cnblogs.com/qinduanyinghua/p/11530709.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!