Given a matrix of m x n elements (m rows, n columns), 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].
The line marked as red need to pay special attention! (It is very easy to forget it!)
I personally think this question is pretty hard...... It has a lot of details to deal with in a limited time and easy to make mistakes.
#include <vector>
#include <iostream>
using namespace std;
vector<int> spiralOrder(vector< vector<int> >& matrix) {
if(matrix.size() == 0) return {};
if(matrix[0].size() == 0) return {};
int m = matrix.size();
int n = matrix[0].size();
vector<int> res;
int layer = m < n ? m : n;
// this is only for even m and n.
for(int i = 0; i < layer/2; ++i) {
for(int j = i; j < n - 1 - i; ++j) {
res.push_back(matrix[i][j]);
}
for(int j = i; j < m - 1 - i; ++j)
res.push_back(matrix[j][n-1-i]);
for(int j = n - 1 - i; j > i; --j)
res.push_back(matrix[m-1-i][j]);
for(int j = m - 1 - i; j > i; --j)
res.push_back(matrix[j][i]);
}
// ends for even m and n.
if(layer % 2 != 0) {
if(m > n) {
for(int i = layer/2; i <= m - 1 - layer/2; ++i) {
res.push_back(matrix[i][n/2]);
}
} else {
for(int i = layer/2; i <= n - 1 - layer/2; ++i) {
res.push_back(matrix[m/2][i]);
}
}
}
return res;
}
int main(void) {
vector< vector<int> > matrix{
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5},
{1, 2, 3, 4, 5}};
vector<int> res = spiralOrder(matrix);
for(int i = 0; i < res.size(); ++i) {
cout << "index i: " << i << " " << res[i] << endl;
}
cout << endl;
}
2: Print matrix diagonally.
/*
1 2 3
4 5 6
7 8 9
10 11 12
the output should be:
1
4 2
7 5 3
10 8 6
11 9
12
*/
void printDiagional(vector< vector<int> >& matrix) {
int rows = matrix.size();
int cols = matrix[0].size();
for(int k = 0; k < rows; ++k) {
int row = k, col = 0;
while(row >= 0 && col <= min(cols - 1, k)) {
cout << matrix[row][col] << " ";
row--;
col++;
}
cout << endl;
}
for(int k = 1; k < cols; ++k) {
int row = 0, col = k;
while((col <= cols - 1) && row <= min(rows, cols - 1 - k)) {
cout << matrix[rows - 1 - row][col] << " ";
col++;
row++;
}
cout << endl;
}
}
int main(void) {
vector< vector<int> > matrix {
{10, 11}};
printDiagional(matrix);
}

本文介绍了一种算法来实现矩阵元素的螺旋顺序遍历,并提供了一个示例程序。此外,还讨论了如何按对角线顺序打印矩阵元素的方法。
504

被折叠的 条评论
为什么被折叠?



