我是靠谱客的博主 勤恳滑板,这篇文章主要介绍输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字 C++实现,现在分享给大家,希望可以做个参考。

题目描述:

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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
2
3
4
5
6
7
8
9
10
11
int main() { Solution a; vector<vector<int>> matrix = { {1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15} };//矩阵初始化 vector<int> m=a.printMatrix(matrix); for(auto i : m)//依次打印返回矩阵的值 cout<<i; return0; }

方法一:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//每次循环找出右上和左下的点作为参考 class Solution{ public: vector<int>printMatrix(vector<vector<int>> matrix) { vector<int>vec; int row = matrix.size(); int column = matrix[0].size(); int count = 0; if(row == 1)//区分行向量和列向量 vec=matrix[0]; elseif(column == 1) { for(int i = 0; i < row; i++) vec.push_back(matrix[i][0]);} else{ for(int m = 0;(m < row - count)&&(m<column-count); m++){ count++; if(column- 1 - m>=m){ int right_up = matrix[m][column- 1 - m]; for(int i = m; i < column - 1 - m; i++) vec.push_back(matrix[m][i]); vec.push_back(matrix[m][column- 1-m]);//右上元素 for(int j = m+1; j < row - m-1; j++) vec.push_back(matrix[j][column-1- m]);} if(row - 1 - m >m){ for(int i = column - 1 - m; (i > m); i--) vec.push_back(matrix[row- 1 - m][i]); vec.push_back(matrix[row- 1 - m][m]);//左下元素 for(int i = row - 1 - m-1; i > m; i--) vec.push_back( matrix[i][m]); }} } return vec; } };

方法二:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//直接定义一个矩形,在矩形的四条边取值,程序大大简化 class Solution{ public: vector<int>printMatrix(vector<vector<int>> matrix) { vector<int>vec; int row = matrix.size(); int column = matrix[0].size(); int left = 0, right = column, up = 0, bottom = row; while((up < bottom) && (left < right)) { for(int i = left; i < right; i++) vec.push_back(matrix[up][i]); for(int i = up+1; i < bottom; i++) vec.push_back(matrix[i][right-1]); for(int i = right-1-1; ((bottom-1)!=up)&&(i >=left); i--) vec.push_back(matrix[bottom-1][i]); for(int i = bottom-1-1; ((right-1)!=left)&&(i >left); i--) vec.push_back(matrix[i][left]); up++;left++; right--; bottom--; } return vec; } };

 

 

最后

以上就是勤恳滑板最近收集整理的关于输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字 C++实现的全部内容,更多相关输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(66)

评论列表共有 0 条评论

立即
投稿
返回
顶部