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]
.对于螺旋打印一个matrix,可以考虑一圈一圈打印,从外圈到内圈是用offset来传递。对于base case 情况的考虑,matrix可能没有元素,或者可能只有一列或者一行
时间复杂度: O(n^2)空间复杂度: O(n)
class Solution {
private:
void helper(vector<int> &rst, vector<vector<int>>& matrix, int row, int col, int offset) {
//base case
if (row <= 0 || col <= 0) return;
if (row == 1 ) {
for (int i = 0; i < col; i++) {
rst.push_back(matrix[offset][i+offset]);
}
return;
}
if (col == 1) {
for (int i = 0; i < row; i++) {
rst.push_back(matrix[offset+i][offset]);
}
return;
}
//from left to right
for (int i = 0; i < col-1; i++) {
rst.push_back(matrix[offset][offset+i]);
}
//from up to down
for (int i = 0; i < row-1; i++) {
rst.push_back(matrix[offset+i][col-1+offset]);
}
//from right to left
for (int i = col-1; i >= 1; i--) {
rst.push_back(matrix[row-1+offset][offset + i]);
}
//from down to up
for (int i = row - 1; i >= 1; i--) {
rst.push_back(matrix[i + offset][offset]);
}
helper(rst, matrix, row - 2, col - 2, offset + 1);
}
public:
//use recursion
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> rst;
//sanity check
if (matrix.size() == 0 || matrix[0].size() == 0) return rst;
helper(rst, matrix, matrix.size(), matrix[0].size(), 0);
return rst;
}
};
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n =
3
,
You should return the following matrix:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ] ]
解法与上题类似, 初始化一个二维矩阵: vector<int> solu(n,0); vector<vector<int>> rst(n,solu);
class Solution { private: void helper( int n, int count , vector<vector<int>> & matrix, int offset){ //base case if (n == 0) return; if (n == 1) { matrix[offset][offset] = count; return; } //from left to right for (int i = 0; i < n-1; i++) { matrix[offset][i+offset] = count++; } //from up to down for (int i = 0; i < n-1; i++) { matrix[offset + i][n-1+offset] = count++; } //from right to left for (int i = n-1; i >= 1; i--) { matrix[offset+ n-1][offset+i] = count++; } //from down to up for (int i = n-1; i >= 1; i--) { matrix[offset+i][offset] = count++; } helper(n-2, count, matrix, offset+1); } public: vector<vector<int>> generateMatrix(int n) { vector<int> solu(n,0); vector<vector<int>> rst(n, solu); //sanity check if (n == 0) return rst; helper(n, 1, rst, 0); return rst; } };
No comments:
Post a Comment