This question is bound to circle around the loop, therefore, consider two questions: 1. How do I end the cycle 2. How to print circle
I'm lazy today, main function is I moved from the answers.
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 class Solution { 5 public: 6 vector<int> printMatrix(vector<vector<int> > matrix) { 7 int row = matrix.size(); 8 int col = matrix[0].size(); 9 int left = 0, right = col-1;//列标 10 int top = 0, bot = row-1; // row index . 11 Vector < int > Result; 12 is the while (left <= right && Top <= BOT) 13 is { 14 // print top row, the column is variable 15 for ( int I = left; I <= right; I ++ ) 16 { . 17 result.push_back (Matrix [Top] [I]); 18 is } . 19 // print the right column, is variable row 20 is IF (BOT> Top) 21 is { 22 is for ( int I = Top +. 1 ; I <= BOT; I ++ ) 23 is { 24 result.push_back (Matrix [I] [right]); 25 } 26 is } 27 // print the lower row, the column is variable 28 IF (BOT> Top && right> left) 29 { 30 for ( int I = right- . 1 ; I> = left; i-- ) 31 is { 32 result.push_back (Matrix [BOT] [I]); 33 is 34 is } 35 } 36 //Left a print line is variable 37 [ IF (Top-BOT> . 1 && right> left) 38 is { 39 for ( int I = bot- . 1 ; I> Top; i-- ) 40 { 41 is result.push_back (Matrix [I ] [left]); 42 is } 43 is } 44 is Top ++ ; 45 Right - ; 46 is bot-- ; 47 left ++ ; 48 49 } 50 return result; 51 } 52 }; 53 int main() 54 { 55 int a1[] = { 1, 2, 3, 4 }; 56 int a2[] = { 5, 6, 7, 8 }; 57 int a3[] = { 9, 10, 11, 12 }; 58 int a4[] = { 13, 14, 15, 16 }; 59 // int a1[] = { 1 }; 60 // int a2[] = { 2 }; 61 // int a3[] = { 3 }; 62 // int a4[] = { 4 }; 63 64 vector<int> vec1(a1, a1 + 4); 65 vector<int> vec2(a2, a2 + 4); 66 vector<int> vec3(a3, a3 + 4); 67 vector<int> vec4(a4, a4 + 4); 68 69 70 vector< vector<int> > vec; 71 vec.push_back(vec1); 72 vec.push_back(vec2); 73 vec.push_back(vec3); 74 vec.push_back(vec4); 75 76 Solution solu; 77 vector<int> res = solu.printMatrix(vec); 78 for (int i = 0; i < res.size(); i++) 79 { 80 cout << res[i] << " "; 81 } 82 return 0; 83 }