[LeetCode] Spiral Matrix

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

 

posted @ 2015-08-11 08:51  jianchao-li  阅读(204)  评论(0编辑  收藏  举报