题目描述:
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in ZigZag-order.
Example
题目思路:
Given a matrix:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10, 11, 12]
]
return [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]
这题也没啥算法可言,就是要好好算好这个index应该放matrix的哪个数,然后一个一个放进去即可。
Mycode(AC = 13ms):
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
vector<int> ans;
int num_row = matrix.size();
if (num_row == 0) return ans;
int num_col = matrix[0].size();
ans.resize(num_row * num_col);
printZMatrix(matrix, ans, 0, 0);
return ans;
}
void printZMatrix(vector<vector<int> > &matrix,
vector<int>& ans,
int col_idx,
int idx)
{
if (idx >= ans.size()) {
return;
}
int index = idx;
// upper line
for (int i = col_idx; i < 2 + col_idx; i++) {
if (i >= 0 && i < matrix[0].size()) {
ans[index++] = matrix[0][i];
}
}
// '/' line
int row = 1, col = col_idx;
while (row < matrix.size()) {
if (col >= 0 && col < matrix[0].size()) {
ans[index++] = matrix[row][col];
}
row++; col--;
}
// bottom line and another '/' line
row--; col += 2;
while (row > 0) {
if (col >= 0 && col < matrix[0].size()) {
ans[index++] = matrix[row][col];
}
row--; col++;
}
printZMatrix(matrix, ans, col_idx + 2, index);
}
};