Spiral Matrix
题目:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5]
分析:定义了一个子函数,每次顺时针访问矩阵的一圈,这样逐步缩小圈
class Solution {
private:
//只打印矩阵的第t圈, m,n分别为矩阵第t圈的行和列
vector<int> orderOneTurn(vector<vector<int>>& matrix, int t, int m, int n)
{
vector<int> res;
if (m < 1 || n < 1)
{
return res;
}
res.reserve(2 * (m + n) - 4);
if (m == 1 || n == 1)
{
for (int j = 0; j < m; ++j)
{
for (int i = 0; i < n; ++i)
{
res.push_back(matrix[j + t][i + t]);
}
}
return res;
}
//i代表列,j代表行
//上
for (int i = 0; i < n - 1; ++i)
{
res.push_back(matrix[t][i + t]);
}
//右
for (int j = 0; j < m - 1; ++j)
{
res.push_back(matrix[j + t][t + n - 1]);
}
//下
for (int i = n - 1; i > 0; --i)
{
res.push_back(matrix[t + m - 1][i + t]);
}
//左
for (int j = m - 1; j > 0; --j)
{
res.push_back(matrix[j + t][t]);
}
return res;
}
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty() || matrix[0].empty())
{
return res;
}
int m = matrix.size(), n = matrix[0].size();
res.reserve(m * n);
int nTurns = (min(m, n) + 1 ) / 2;
for (int t = 0; t < nTurns; ++t)
{
vector<int> oneTurn = orderOneTurn(matrix, t, m - 2 * t, n - 2 * t);
std::copy(oneTurn.begin(), oneTurn.end(), std::back_inserter(res));
}
return res;
}
};
Spiral Matrix II
题目:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3
,
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
分析:
类似于蛇吃蛋,因为访问过的位置已经不是0了,从左上角向右行走,遇到障碍(矩阵边界或者非0)就右拐,直到无路可走。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if (n <= 0)
{
return vector<vector<int>>();
}
vector<vector<int>> res(n, vector<int>(n, 0));
int i = 0, j = 0;//出发点
int label = 1;
res[i][j] = label;
int nElements = n * n;
while (label < nElements)
{
while (j < n - 1 && res[i][j + 1] == 0)
{
++j;//向右
res[i][j] = ++label;
}
while (i < n - 1 && res[i + 1][j] == 0)
{
++i;//向下
res[i][j] = ++label;
}
while (j > 0 && res[i][j - 1] == 0)
{
--j;//向左
res[i][j] = ++label;
}
while (i > 0 && res[i - 1][j] == 0)
{
--i;//向上
res[i][j] = ++label;
}
}
return res;
}
};