185-矩阵的之字型遍历
给你一个包含 m x n 个元素的矩阵 (m 行, n 列), 求该矩阵的之字型遍历。
样例
对于如下矩阵:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10, 11, 12]
]
返回 [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]标签
LintCode 版权所有 矩阵
思路
参考http://blog.csdn.net/wutingyehe/article/details/46629087
code
class Solution {
public:
/**
* @param matrix: a matrix of integers
* @return: a vector of integers
*/
vector<int> printZMatrix(vector<vector<int> > &matrix) {
// write your code here
int sizeRow = matrix.size();
if (sizeRow <= 0) {
return vector<int>();
}
int sizeCol = matrix[0].size();
if (sizeCol <= 0) {
return vector<int>();
}
vector<int> result;
int count = sizeRow * sizeCol, curRow = 0, curCol = 0;
result.push_back(matrix[0][0]);
for (int i = 1; i < count; ) {
//斜上走到顶
while (i < count && curRow - 1 >= 0 && curCol + 1 < sizeCol) {
result.push_back(matrix[--curRow][++curCol]);
i++;
}
//横右走一步,不可横右走时竖下走一步
if (i < count && curCol + 1 < sizeCol) {
result.push_back(matrix[curRow][++curCol]);
i++;
}
else if (i < count && curRow + 1 < sizeRow) {
result.push_back(matrix[++curRow][curCol]);
i++;
}
//斜下走到底
while (i < count && curRow + 1 < sizeRow && curCol - 1 >= 0) {
result.push_back(matrix[++curRow][--curCol]);
i++;
}
//竖下走一步,不可竖下走时横右走一步
if (i < count && curRow + 1 < sizeRow) {
result.push_back(matrix[++curRow][curCol]);
i++;
}
else if (i < count && curCol + 1 < sizeCol) {
result.push_back(matrix[curRow][++curCol]);
i++;
}
}
return result;
}
};