54. Spiral Matrix (Graph)
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]
.
思路:创建函数互相递归调用,函数的参数要包括方向
class Solution { public: vector<int> spiralOrder(vector<vector<int>> &matrix) { // Start typing your C/C++ solution below // DO NOT write int main() function result.clear(); if(matrix.empty()) return result; leftPos = 0; rightPos = matrix[0].size()-1; topPos = 0; bottomPos = matrix.size()-1; goWider(matrix, true); return result; } void goWider(vector<vector<int>> &matrix, bool direct) { if(direct) { for(int i = leftPos; i<= rightPos; i++) { result.push_back(matrix[topPos][i]); } topPos++; if(topPos > bottomPos) return; goDeeper(matrix, true); } else { for(int i = rightPos; i>= leftPos; i--) { result.push_back(matrix[bottomPos][i]); } bottomPos--; if(topPos > bottomPos) return; goDeeper(matrix, false); } } void goDeeper(vector<vector<int>> &matrix, bool direct) { if(direct) { for(int i = topPos; i<= bottomPos; i++) { result.push_back(matrix[i][rightPos]); } rightPos--; if(leftPos > rightPos) return; goWider(matrix, false); } else { for(int i = bottomPos; i>= topPos; i--) { result.push_back(matrix[i][leftPos]); } leftPos++; if(leftPos > rightPos) return; goWider(matrix, true); } } private: vector<int> result; int leftPos; int rightPos; int topPos; int bottomPos; };