剑指offer19:按照从外向里以顺时针的顺序依次打印出每一个数字,4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
1 题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
2 思路和方法
直接定义一个矩形,在矩形的四条边取值,程序大大简化。
3 核心代码
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 };
4 完整代码
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