59. Spiral Matrix II
2016-06-27 22:28
459 查看
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:
题意:给一个数n,按螺旋方式把 值1--n^2之间的数填入矩阵。
思路:跟spiral matrix题目一样,重点是对matrix的螺旋式遍历方法。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
if (n < 1)
return matrix;
int i = 0;
int j = 0;
int count = 1;
matrix[i][j] = count++;
const int nn = n*n;
while (count <= nn){
//turn right
while (j + 1 < n - i && count <= nn){
matrix[i][++j] = count++;
}
//turn down
while (i + 1 < n - (n - j - 1) && count <= nn){
matrix[++i][j] = count++;
}
//turn left
while (j - 1 >= n - i - 1 && count <= nn){
matrix[i][--j] = count++;
}
//turn up
while (i - 1 >= j + 1 && count <= nn){
matrix[--i][j] = count++;
}
}
return matrix;
}
};
For example,
Given n =
3,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
题意:给一个数n,按螺旋方式把 值1--n^2之间的数填入矩阵。
思路:跟spiral matrix题目一样,重点是对matrix的螺旋式遍历方法。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
if (n < 1)
return matrix;
int i = 0;
int j = 0;
int count = 1;
matrix[i][j] = count++;
const int nn = n*n;
while (count <= nn){
//turn right
while (j + 1 < n - i && count <= nn){
matrix[i][++j] = count++;
}
//turn down
while (i + 1 < n - (n - j - 1) && count <= nn){
matrix[++i][j] = count++;
}
//turn left
while (j - 1 >= n - i - 1 && count <= nn){
matrix[i][--j] = count++;
}
//turn up
while (i - 1 >= j + 1 && count <= nn){
matrix[--i][j] = count++;
}
}
return matrix;
}
};
相关文章推荐
- C#使用Matrix执行缩放的方法
- 如何使用Matrix对bitmap的旋转与镜像水平垂直翻转
- 如何利用matrix实现图片倒影效果
- Android中Matrix用法实例分析
- Android中使用Matrix控制图形变换和制作倒影效果的方法
- HP Z800 Workstation - Configuring RAID devices (HP Z800 做磁盘Raid1,Raid0的阵列)
- Android Matrix类以及ColorMatrix类详解
- 用css实现图片的旋转
- 让舞台上的按钮btn灰掉
- Android中Bitmap和Drawable
- Matrix 详解
- Android 简单的图片缩放方法
- Feelings after the test.
- 用于线性代数的Ruby模块linalg 0.32发布收藏(来自ruby-talk)
- Android之涂鸦(简单的画图)
- c++ Primer 之 类的初始化,赋值和析构
- 哪部电影是技术人员最应该看的?
- 堆
- .Net的内存管理,非托管资源的处理原则
- Machine Learning Week 2