[LeetCode] Spiral Matrix II

The idea is just to generate the matrix 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 generating a row or a column, update the corresponding variable to continue the generation.

The code is as follows.

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

 

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