54. Spiral Matrix
Given a matrix ofmxnelements (mrows,ncolumns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return[1,2,3,6,9,8,7,4,5]
.
S:
从四周到中间分行列存入数组
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int n = matrix.size();
if (n == 0) return vector<int>{};
int m = matrix[0].size();
vector<int> result(m * n);
int maxLevel = ceil(min(m, n) / 2.0);
int idx = 0;
for (int i = 0; i < maxLevel; ++i) {
int row1 = i, row2 = n - i - 1, col1 = i, col2 = m - i - 1;
for (int j = col1; j <= col2; ++j) {
result[idx++] = matrix[row1][j];
}
for (int j = row1 + 1; j <= row2; ++j) {
result[idx++] = matrix[j][col2];
}
if (row2 > row1) {
for (int j = col2 - 1; j >= col1; --j) {
result[idx++] = matrix[row2][j];
}
}
if (col2 > col1) {
for (int j = row2 - 1; j > row1; --j) {
result[idx++] = matrix[j][col1];
}
}
}
return result;
}
498. Diagonal Traverse
Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output:
[1,2,4,7,5,3,6,8,9]
Explanation:
Note:
- The total number of elements of the given matrix will not exceed 10,000.
S
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
int m = matrix.size();
if (m == 0) return vector<int>{};
int n = matrix[0].size();
vector<int> result(m * n);
vector<int> dx{-1, 1};
vector<int> dy{1, -1};
int dir = 0;
for (int x = 0, y = 0, i = 0; i < m * n; ++i) {
result[i] = matrix[x][y];
int idx = dir % 2;
if (y < n - 1 && ((x == 0 && idx == 0) || (x == m - 1 && idx == 1))) {
y++;
dir++;
} else if (x < m - 1 && ((y == 0 && idx == 1) || (y == n - 1 && idx == 0))) {
x++;
dir++;
} else {
x += dx[idx];
y += dy[idx];
}
}
return result;
}