Loading

剑指 Offer 29. 顺时针打印矩阵

思路

模拟。思路来自:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/solution/mian-shi-ti-29-shun-shi-zhen-da-yin-ju-zhen-she-di/

 

代码实现

 1 class Solution {
 2 private:
 3     vector<int> res;
 4     int n, m;
 5 public:
 6     vector<int> spiralOrder(vector<vector<int>>& matrix) {
 7         //n行m列
 8         n = matrix.size();
 9         if(n == 0) return res;
10         m = matrix[0].size();
11         if(m == 0) return res;
12         
13         int i = 0, j = 0;
14         int r = m-1, b = n-1, l = 0, t = 0;
15 
16         while(1) {
17             for(int i = l; i <= r; ++i)
18                 res.push_back(matrix[t][i]);
19             if(++t > b)
20                 break;
21 
22             for(int i = t; i <= b; ++i)
23                 res.push_back(matrix[i][r]);
24             if(--r < l)
25                 break;
26             
27             for(int i = r; i >= l; --i)
28                 res.push_back(matrix[b][i]);
29             if(--b < t)
30                 break;
31 
32             for(int i = b; i >= t; --i)
33                 res.push_back(matrix[i][l]);
34             if(++l > r)
35                 break;
36         }
37 
38         return res;
39     }
40 };

 

复杂度分析

 

posted @ 2020-10-28 13:45  拾月凄辰  阅读(81)  评论(0编辑  收藏  举报