差一点点就写出来的题,不过这也是一种难忘的经验吧!
螺旋矩阵I
给定一个 m 行 n 列的矩阵 matrix ,请按照顺时针螺旋顺序 ,返回矩阵中的所有元素(一维数组)。
解题思路一
模拟。从左至右->从上至下->从右至左->从下至上,然后重复这个过程。当越界时跳出循环即可。
代码如下(输出结果为一维数组)
vector<int> spiralOrder(vector<vector<int>>& matrix) {
//如果为空,直接返回一个空数组
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int rows = matrix.size(), columns = matrix[0].size();
vector<int> res;
int left = 0, right = columns - 1, up = 0, bottom = rows - 1;
//当左指针<右指针,上指针<下指针时执行下述while循环,之后左右上下指针依次增减
while (left <= right && up <= bottom) {
//先遍历行
for (int column = left; column <= right; column++) {
res.push_back(matrix[up][column]);
}
//再遍历列
for (int row = up + 1; row <= bottom; row++) {
res.push_back(matrix[row][right]);
}
//螺旋部分需要单独做判断
if (left < right && up < bottom) {
for (int column = right - 1; column > left; column--) {
res.push_back(matrix[bottom][column]);
}
for (int row = bottom; row > up; row--) {
res.push_back(matrix[row][left]);
}
}
left++;
right--;
up++;
bottom--;
}
//打印一下螺旋遍历结束的数组
for(int i = 0; i < res.size(); i++) {
cout << res[i] << endl;
}
return res;
}
int main() {
vector<vector<int>> matrix = { {1,2,3}, {4,5,6}, {7,8,9}};//请注意,矩阵里面第一个空格是必要的!否则无法build完成
spiralOrder(matrix);
return 0;
}
螺旋矩阵II
- 给定参数m和n,要求返回一个m行n列的螺旋矩阵。
解题思路
代码如下
#include <iostream>
#include <vector>
using namespace std;
void generateMatrix(int m, int n) {
int num = 1;
vector<vector<int> > matrix(m, vector<int>(n));
int left = 0, right = n - 1, top = 0, bottom = m - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
matrix[top][column] = num;
num++;
}
for (int row = top + 1; row <= bottom; row++) {
matrix[row][right] = num;
num++;
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
matrix[bottom][column] = num;
num++;
}
for (int row = bottom; row > top; row--) {
matrix[row][left] = num;
num++;
}
}
left++;
right--;
top++;
bottom--;
}
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
int main() {
generateMatrix(4, 3);
return 0;
}