leetcode——59——Spiral Matrix II
2016-04-17 10:58
351 查看
Given an integer n, generate a square matrix filled with elements from 1 to
n2 in spiral order.
For example,
Given n =
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
n2 in spiral order.
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
class Solution { public: vector<vector<int>> generateMatrix(int n) { if (n <= 0) return vector<vector<int>>(); vector<vector<int>> matrix(n, vector<int>(n, 0)); int start = 1; n = n-1; for (int x = 0, y = 0; x <= n && y <= n; x++, y++) { //输出矩阵首行 for (int j = y; j <= n; ++j) { matrix[x][j] = start++; }//while //输出矩阵最右列 for (int i = x + 1; i <= n; ++i) { matrix[i] = start++; }//while //输出矩阵最底行 for (int j = n - 1; j >= y && x != n; --j) { matrix [j] = start++; } //输出矩阵最左列 for (int i = n - 1; i > x && y != n; --i) { matrix[i][y] = start++; } n--; }//for return matrix; } };
相关文章推荐
- [HDU 5667] Sequence (矩阵快速幂+费马小定理)
- 数据持久化-Plist
- OpenCV中的CV_EXPORT是什么意思
- 算法复习之选择排序
- 读者写者问题
- android图片的缓存--节约内存提高程序效率
- 主机开启后,显示器显示NO SIGNAL,无信号
- nefu500网购【二分+网络流】
- 算法复习之快排
- 24. Swap Nodes in Pairs
- 显示联系人列表2 分类标题栏
- 浅谈管道模型(Pipeline)
- mac 下安装 mongodb
- Poco 之cppunit解读
- 进程调度
- 端口表
- Android LayoutInflater详解
- 算法复习之快排
- MAC下 Redis php扩展安装
- maven如何修改本地仓库与中央仓库