Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
Example 1:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5]
Example 2:
Input: [ [1, 2, 3, 4], [5, 6, 7, 8], [9,10,11,12] ] Output: [1,2,3,4,8,12,11,10,9,5,6,7]
code
#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> res; if(matrix.empty()) return res; else if(matrix.size()==1) return matrix.at(0); int direction=0; int top=0,bottom=matrix.size()-1; int left=0,right=matrix.at(0).size()-1; while(true) { if(top>bottom||left>right) break; if(direction%4==0) { for(int i=left;i<=right;++i) res.push_back(matrix.at(top).at(i)); ++top; } else if(direction%4==1) { for(int i=top;i<=bottom;++i) res.push_back(matrix.at(i).at(right)); --right; } else if(direction%4==2) { for(int i=right;i>=left;--i) res.push_back(matrix.at(bottom).at(i)); --bottom; } else if(direction%4==3) { for(int i=bottom;i>=top;--i) res.push_back(matrix.at(i).at(left)); ++left; } ++direction; } return res; } }; int main() { vector<vector<int>> arr{{1,2,3},{4,5,6},{7,8,9}}; Solution s; vector<int> res(s.spiralOrder(arr)); for(auto i:res) cout<<i<<" "; cout<<endl; return 0; }
vector<int> spiralOrder(vector<vector<int>>& matrix) { if ( !matrix.size() || !matrix[0].size() ) return vector<int>(); vector<int> spiral(matrix.size()*matrix[0].size()); vector<vector<int>> dirs = {{0,1},{1,0},{0,-1},{-1,0}}; vector<int> numColsRows = { matrix[0].size(), matrix.size()-1 }; vector<int> cellIndex = {0,-1}; int nPasses = 0, k = 0; while ( k < spiral.size() ) { // iterate to end of current column (%=0) or row (%=1) for (int i = 0; i < numColsRows[nPasses%2]; i++ ) { // advance one cell and copy cellIndex[0] += dirs[nPasses%4][0]; cellIndex[1] += dirs[nPasses%4][1]; spiral[k++] = matrix[cellIndex[0]][cellIndex[1]]; } // decrement number of rows or columns for next pass numColsRows[nPasses%2]--; nPasses++; } return spiral; }