59. Spiral Matrix II
来源:互联网 发布:淘宝网女士套装阔腿裤 编辑:程序博客网 时间:2024/05/01 22:25
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
思路:直接打印即可,注意直接赋值要初始化(push_back的不用),还有n为基数的时候要处理最后中间的那个点。
class Solution {public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res(n, vector<int>(n,0)); //记得初始化 int left = 0, right = n-1, top = 0, bottom = n -1; int k = 1; while(left < right && top < bottom) { for(int j =left; j < right; j++) { res[top][j] = k++; } for(int j = top; j < bottom; j++) { res[j][right] = k++; } for(int j = right; j > left; j--) { res[bottom][j] = k++; } for(int j = bottom; j > top; j--) { res[j][left] = k++; } top++; bottom--; left++; right--; } if(n%2 == 1) { res[n/2][n/2] = k; } return res; }};
0 0
- 59.Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 59. Spiral Matrix II
- 使用Picasso加载图片
- 一个新的图像格式 -- webp介绍
- C++ primer plus读书笔记(四)
- 自建 AppRTC【转】
- python_HTTP(实现GET、PUT、POST、DELETE操作)
- 59. Spiral Matrix II
- 实战录 | Hadoop Mapreduce shuffle之Combine探讨
- Jmeter逻辑控制器(转自Jmeter之逻辑控制器(Logic Controller)-贺满)
- sf
- ngrok实现域名映射外网
- HDU 1102 Constructing Roads (kruskal)
- C深度解刨笔记
- 单词查找树
- 仿微信/支付宝的密码输入框效果:GridPasswordView