标签:matrix row tor 打印 push desc div 顺序 while
直接定义一个矩形,在矩形的四条边取值,程序大大简化。
1 class Solution { 2 public: 3 vector<int> printMatrix(vector<vector<int> > matrix) { 4 vector<int>vec; 5 int row = matrix.size(); 6 int column = matrix[0].size(); 7 int left = 0, right = column, up = 0, bottom = row; 8 while((up < bottom) && (left < right)) 9 { 10 for(int i = left; i < right; i++) vec.push_back(matrix[up][i]); 11 for(int i = up+1; i < bottom; i++) vec.push_back(matrix[i][right-1]); 12 for(int i = right-1-1; ((bottom-1)!=up)&&(i >=left); i--) vec.push_back(matrix[bottom-1][i]); 13 for(int i = bottom-1-1; ((right-1)!=left)&&(i >left); i--) vec.push_back(matrix[i][left]); 14 up++;left++; right--; bottom--; 15 } 16 return vec; 17 } 18 };
1 #include<iostream> 2 #include<vector> 3 4 using namespace std; 5 6 //直接定义一个矩形,在矩形的四条边取值,程序大大简化 7 class Solution{ 8 public: 9 vector<int>printMatrix(vector<vector<int>> matrix) { 10 vector<int>vec; 11 int row = matrix.size(); 12 int column = matrix[0].size(); 13 int left = 0, right = column, up = 0, bottom = row; 14 while ((up < bottom) && (left < right)) 15 { 16 for (int i = left; i < right; i++) vec.push_back(matrix[up][i]); 17 for (int i = up + 1; i < bottom; i++) vec.push_back(matrix[i][right - 1]); 18 for (int i = right - 1 - 1; ((bottom - 1) != up) && (i >= left); i--) vec.push_back(matrix[bottom - 1][i]); 19 for (int i = bottom - 1 - 1; ((right - 1) != left) && (i >left); i--) vec.push_back(matrix[i][left]); 20 up++; left++; right--; bottom--; 21 } 22 return vec; 23 } 24 }; 25 26 int main() 27 28 { 29 Solution a; 30 vector<vector<int>> matrix = { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 } };//矩阵初始化 31 vector<int> m = a.printMatrix(matrix); 32 for (auto i : m)//依次打印返回矩阵的值 33 cout << i << " "; 34 cout << endl; 35 36 return 0; 37 38 }
https://blog.csdn.net/hangsyt108/article/details/80949337
标签:matrix row tor 打印 push desc div 顺序 while
原文地址:https://www.cnblogs.com/wxwhnu/p/11410207.html