螺旋数组

顺时针打印矩阵

http://www.nowcoder.com/questionTerminal/9b4c81a02cd34f76be2659fa0d54342a

class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
// 矩阵的螺旋序列
// 初始化vis记录是否被访问过
vector<int> res;
int row = matrix.size(), col = matrix[0].size();
vector<vector<int>> vis(row, vector<int>());//初始层数,赋值
for (int i = 0; i < row; i ++) {
vis[i].resize(col);
}
int x = 0, y = 0;
while(true) {
// 依次先向右,再向下,再向左,再向上,每次更新vis
for(; y < col && !vis[x][y]; y ++) res.push_back(matrix[x][y]), vis[x][y] = 1;
y --; x ++;
for(; x < row && !vis[x][y]; x ++) res.push_back(matrix[x][y]), vis[x][y] = 1;
x --; y --;
for(; y >= 0 && !vis[x][y]; y --) res.push_back(matrix[x][y]), vis[x][y] = 1;
y ++; x --;
for(; x >= 0 && !vis[x][y]; x --) res.push_back(matrix[x][y]), vis[x][y] = 1;
x ++; y ++;
if(res.size() == row * col) break;
}
return res;
}
};</int></int></int></int></int>

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务