1.生成矩阵
class Solution {
public:
vector<vector<int> > creatMatrix(int n) {
vector<vector<int> > mat(n, vector<int>(n, 0));
int val = 1;
if (n <= 0)
return mat;
if (n == 1)
return { {1} };
int right = n - 1;
int left = 0;
int top = 0;
int bottom = n - 1;
while (top <= bottom && left <= right) {
//左到右
for (int i = left; i <= right; i++)
mat[top][i] = val++;
//上到下
for (int i = top + 1; i <= bottom; i++)
mat[i][right] = val++;
//右到左
if (top != bottom) {
for (int i = right - 1; i >= left; i--)
mat[bottom][i] = val++;
}
//下到上
if (left != right) {
for (int i = bottom - 1; i > top; i--)
mat[i][left] = val++;
}
right--; left++; top++; bottom--;
}
return mat;
}
};
2.打印矩阵
class Solution {
public:
vector<int> creatMatrix(vector<vector<int> > mat) {
int m = mat.sise();
int n = mat[0].size();
vector<int> res;
if (n <= 0)
return res;
int right = n - 1;
int left = 0;
int top = 0;
int bottom = m - 1;
while (top <= bottom && left <= right) {
//左到右
for (int i = left; i <= right; i++)
res.push_back(mat[top][i]);
//上到下
for (int i = top + 1; i <= bottom; i++)
res.push_back(mat[i][right);
//右到左
if (top != bottom) {
for (int i = right - 1; i >= left; i--)
res.push_back(mat[bottom][i]);
}
//下到上
if (left != right) {
for (int i = bottom - 1; i > top; i--)
res.push_back(mat[i][left]);
}
right--; left++; top++; bottom--;
}
return res;
}
};