LeetCode 59. 螺旋矩阵 II(Spiral Matrix II)

题目描述

 

给定一个正整数 n,生成一个包含 1 到 n2 所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

示例:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

 

解题思路

 

LeetCode54.螺旋矩阵 的思想差不多,定义左上角的行索引,然后依次从左至右、从上至下、从右至左、从下至上遍历,注意起始索引和终止索引。

 

代码

 

 1 class Solution {
 2 public:
 3     vector<vector<int>> generateMatrix(int n) {
 4         vector<vector<int>> res(n, vector<int>(n, 0));
 5         int idx = 0, num = 1;
 6         while(idx * 2 < n){
 7             for(int col = idx; col < n - idx; col++)
 8                 res[idx][col] = num++;
 9             for(int row = idx + 1; row < n - idx; row++)
10                 res[row][n - idx - 1] = num++;
11             for(int col = n - idx - 2; col >= idx; col--)
12                 res[n - idx - 1][col] = num++;
13             for(int row = n - idx - 2; row > idx; row--)
14                 res[row][idx] = num++;
15             idx++;
16         }
17         return res;
18     }
19 };

 

posted @ 2018-07-30 16:05  FlyingWarrior  阅读(437)  评论(0编辑  收藏  举报