#include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> printMatrix(vector<vector<int> > matrix) { int row = matrix.size(); int col = matrix[0].size(); vector<vector<int>> vis(row, vector<int>(col, 0)); int step_x[4] = {0,1,0,-1}, step_y[4] = {1,0,-1,0}; int flag = 0; vector<int> res; res.push_back(matrix[0][0]); int i=0,j=0; vis[i][j] = 1; while(1) { if(res.size() == row*col) break; i += step_x[flag%4], j += step_y[flag%4]; if(i>=0 && j >=0 && i < row && j < col && vis[i][j] == 0) { res.push_back(matrix[i][j]); vis[i][j] = 1; } else { i -= step_x[flag%4], j -= step_y[flag%4]; flag++; } } return res; } }; int main() { // insert code here... Solution sol; vector<vector<int>> matrix ={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; vector<int> res = sol.printMatrix(matrix); for(auto i:res) cout << i << endl; return 0; }