トピック
ソードフィンガーオファー29.マトリックスを時計回りに印刷するマトリックスを
入力し、外側から内側に向かって時計回りに各番号を印刷します。
例1:
入力:matrix = [[1,2,3]、[4,5,6]、[7,8,9]]
出力:[1,2,3,6,9,8,7,4 、5]
例2:
入力:matrix = [[1,2,3,4]、[5,6,7,8]、[9,10,11,12]]
出力:[1,2,3,4,8 、12、11、10、9、5、6、7]
制限制:
0 <= matrix.length <= 100
0 <= matrix [i] .length <= 100
コード
- 再帰的思考
- 毎回「口」の形をした時計回りの数字を取得します。
- 各「口」グリフについて、開始点の座標(左上の点)と行と列の数を知る必要があるだけです。
- (start_row、start_col)を想定した開始点座標
- row_lenを想定した行数
- col_lenを想定した列数
- 外層と内層の間の「口」の形状の関係は、開始点の座標が両方とも+1であり、行と列の数が両方とも-2であるということです。
- 最内層にはいくつかの異なる状況があります。
- "。" 3 * 3マトリックスなどのグリフ
- 3 * 4マトリックスなどの「1」フォント
- 「|」グリフ(4 * 3マトリックスなど)
- 4 * 4マトリックスなどの「口」グリフ
- コード
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
int row = matrix.size();
if (0 == row) {
return vector<int>();
}
int col = matrix[0].size();
if (0 == col) {
return vector<int>();
}
return getCircle(matrix, 0, 0, row, col);
}
private:
vector<int> getCircle(vector<vector<int>>& matrix,
int start_row,
int start_col,
int row_len,
int col_len) {
if (row_len < 1 || col_len < 1) {
return vector<int>();
}
vector<int> res;
if (1 == row_len && 1 == col_len) {
// .
res.push_back(matrix[start_row][start_col]);
} else if (1 == row_len) {
// ——
for (int i = 0; i < col_len; ++i) {
res.push_back(matrix[start_row][start_col + i]);
}
} else if (1 == col_len) {
// |
for (int i = 0; i < row_len; ++i) {
res.push_back(matrix[start_row + i][start_col]);
}
} else {
// 口
for (int i = 0; i < col_len; ++i) {
res.push_back(matrix[start_row][start_col + i]);
}
for (int i = 1; i < row_len; ++i) {
res.push_back(matrix[start_row + i][start_col + col_len - 1]);
}
for (int i = col_len - 2; i >= 0; --i) {
res.push_back(matrix[start_row + row_len - 1][start_col + i]);
}
for (int i = row_len - 2; i > 0; --i) {
res.push_back(matrix[start_row + i][start_col]);
}
}
auto inner_circle = getCircle(matrix, start_row + 1, start_col + 1,
row_len - 2, col_len - 2);
copy(inner_circle.begin(), inner_circle.end(), back_inserter(res));
return res;
}
};
テスト
#include <iostream>
int main() {
Solution s;
{
vector<vector<int>> matrix{
{
1, 2, 3, 4}, {
5, 6, 7, 8}, {
9, 10, 11, 12}};
auto res = s.spiralOrder(matrix);
for (auto i : res) {
cout << i << " ";
}
cout << endl;
}
{
vector<vector<int>> matrix{
{
3}, {
2}};
auto res = s.spiralOrder(matrix);
for (auto i : res) {
cout << i << " ";
}
}
cin.get();
return 0;
}
- 結果
1 2 3 4 8 12 11 10 9 5 6 7
3 2