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

[LeetCode] Spiral Matrix

时间:2015-08-11 09:44:52      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:

The idea is just to add the elements in the spiral order. First the up-most row (u), then the right-most column (r), then the down-most row (d), and finally the left-most column (l). After finishing a row or a column, update the corresponding variable to continue the process.

The code is as follows.

 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
 4         if (matrix.empty()) return {};
 5         int m = matrix.size(), n = matrix[0].size();
 6         vector<int> spiral(m * n);
 7         int u = 0, d = m - 1, l = 0, r = n - 1, k = 0;
 8         while (true) {
 9             // up
10             for (int col = l; col <= r; col++) spiral[k++] = matrix[u][col];
11             if (++u > d) break;
12             // right
13             for (int row = u; row <= d; row++) spiral[k++] = matrix[row][r];
14             if (--r < l) break;
15             // down
16             for (int col = r; col >= l; col--) spiral[k++] = matrix[d][col];
17             if (--d < u) break;
18             // left
19             for (int row = d; row >= u; row--) spiral[k++] = matrix[row][l];
20             if (++l > r) break;
21         }
22         return spiral;
23     }
24 };

 

[LeetCode] Spiral Matrix

标签:

原文地址:http://www.cnblogs.com/jcliBlogger/p/4719962.html

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