59. Spiral Matrix II
来源:互联网 发布:淘宝快递投诉怎么撤销 编辑:程序博客网 时间:2024/06/05 15:35
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 ]]
这道题的思路和54. Spiral Matrix的思路十分相似,先初始化一个n*n的二维数组,然后通过colBegin,colEnd,rowBegin,rowEnd四个值来实现旋转顺序赋值。
利用vector实现二维数组的方法:resize()函数
使用vector构造二维数组
class Solution {public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> ans(n); for (int i = 0; i < n; i++) { ans[i].resize(n); } if (n == 0) return ans; int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1; int num = 1; while (rowBegin <= rowEnd && colBegin <= colEnd) { for (int i = colBegin; i <= colEnd; i++) { ans[rowBegin][i] = num; num++; } rowBegin++; for (int i = rowBegin; i <= rowEnd; i++) { ans[i][colEnd] = num; num++; } colEnd--; if (rowBegin <= rowEnd) { for (int i = colEnd; i >= colBegin; i--) { ans[rowEnd][i] = num; num++; } rowEnd--; } if (colBegin <= colEnd) { for (int i = rowEnd; i >= rowBegin; i--) { ans[i][colBegin] = num; num++; } colBegin++; } } return ans; }};
阅读全文
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
- Spark SQL & Spark Hive编程开发, 并和Hive执行效率对比
- UI_布局之线性布局-动态生成与LayoutInflater
- jdbc报错 :com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
- Openmeetings4.0.0二次开发日志(三)使用webservice调用OM接口(1)
- 机器学习算法之卷积神经网络CNN
- 59. Spiral Matrix II
- C++ 和 Java 的相似点和不同点
- cJson的用法(一) -C语言解析/生成 json数据
- CentOS 6.4 服务器版安装教程(超级详细图解)
- Spring 学习笔记(12)—— AOP 基础
- QT--项目文件的编写方法和qmake的使用
- jquery判断复选框是否选中
- Codeforces#449 (Div. 2)C 字符串递归处理
- 474. Ones and Zeroes