题目
- 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
- 数据范围
矩阵中元素数量 [0,400]。
示例
- 示例1
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出:
[1,2,3,4,8,12,11,10,9,5,6,7]
代码
- 解法:
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int>res;
if(matrix.empty() || matrix[0].empty()) return res;
int row = matrix.size();
int col = matrix[0].size();
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
vector<vector<bool>> st(row,vector<bool>(col,false));
int x = 0,y = 0;
st[x][y] = true;
res.push_back(matrix[x][y]);
for(int i = 0; i < 4; i++){
if(res.size() == row*col) return res;
while(x+dx[i] >= 0 && x+dx[i] < row && y+dy[i] >= 0 && y+dy[i] < col && !st[x+dx[i]][y+dy[i]]){
x += dx[i]; y += dy[i];
st[x][y] = true;
res.push_back(matrix[x][y]);
}
if(i == 3) i = -1;
}
return res;
}
};
代码分析
:没想到能 AC,刺激
遍历的方向依次为上右下左
。先往上遍历,一旦越界或者已访问,就向右遍历....直到返回向量的长度等于整个矩阵的元素个数。
- y总代码
class Solution {
public:
vector<int> printMatrix(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) return res;
int n = matrix.size(), m = matrix[0].size();
vector<vector<bool>> st(n, vector<bool>(m, false));
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
int x = 0, y = 0, d = 1;
for (int k = 0; k < n * m; k ++ )
{
res.push_back(matrix[x][y]);
st[x][y] = true;
int a = x + dx[d], b = y + dy[d];
if (a < 0 || a >= n || b < 0 || b >= m || st[a][b])
{
d = (d + 1) % 4;
a = x + dx[d], b = y + dy[d];
}
x = a, y = b;
}
return res;
}
};
还是 y 总的代码更为简洁
- 空复O(1)解法
使用top、bottom、left、right表示边界
当超出某个边界时,调整边界:
- 超出右边界(y > right)时,上边界加1(++top)
- 超出下边界(x > bottom)时,右边界减1(–right)
- 超出左边界(y < left)时,下边界减1(–bottom)
- 超出上边界(x < top)时,左边界加1(++left)
class Solution {
public:
static vector<int> printMatrix(const vector<vector<int>> &matrix) {
vector<int> res;
if (matrix.empty() || matrix.front().empty()) {
return res;
}
const int m = static_cast<int>(matrix.size());
const int n = static_cast<int>(matrix.front().size());
res.resize(m * n);
// 方向: 右, 下, 左, 上
const int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
int d = 0;
int top = 0, bottom = m - 1, left = 0, right = n - 1; // 边界
// 初始位置: (0, -1)
int i = 0, j = -1;
for (int k = 0; k < m * n;) {
const int x = i + dx[d], y = j + dy[d];
if (x >= top && x <= bottom && y >= left && y <= right) {
res[k] = matrix[x][y];
i = x;
j = y;
++k;
} else {
// 调整边界
if (y > right) {
++top;
} else if (x > bottom) {
--right;
} else if (y < left) {
--bottom;
} else /*if (x < top)*/ {
++left;
}
// 调整方向
++d;
d &= 3;
}
}
return res;
}
};
题目
:顺时针打印矩阵