/* topic: Enter a matrix, in order from outside to inside of a clockwise turn each digital printing. */ /* Ideas: 1, the printing matrix is considered as a print from the outside of the ring. 2, each ring has a start node, coordinates of the starting node * 2 less than the number of rows and columns. 3, for each ring, each printed from left to right, top to bottom, right to left, from the bottom to the figures. */ #include<iostream> #include<string.h> #include<algorithm> #include<cmath> #include<stdio.h> #include<vector> using namespace std; // res pass by reference void printMatrixs(vector<vector<int> > mat,int rows,int columns,int start,vector<int> &res){ int right = columns - start; int down = rows -start; // print a line from left to right for(int i = start; i < right; i++){ res.push_back(mat[start][i]); } // print one from top to bottom for(int i = start + 1; i < down; i++){ res.push_back(mat[i][right-1]); } // print a line from right to left, not left and right to print duplicate lines if(down - 1 != start){ for(int i = right - 2; i >= start; i--){ res.push_back(mat[down-1][i]); } } // print from a lower to a not printed upside down and repeating the column if(start != right - 1){ for(int i = down - 2; i > start; i--){ res.push_back(mat[i][start]); } } } vector<int> clockwisePrint(vector<vector<int>> mat, int rows, int columns) { if(rows == 0 || columns == 0) throw("invalid parameters"); int start = 0; vector<int> res; while(start*2 < rows && start*2 <columns){ printMatrixs(mat,rows,columns,start,res); start++; } return res; } int main () { vector<vector<int>> mat = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}}; vector<int> res = clockwisePrint(mat,4,4); for(int i = 0; i < res.size(); i++){ cout<<res[i]<<" "; } }