[剑指offer]顺时针打印矩阵
来源:互联网 发布:五大基础设施网络建设 编辑:程序博客网 时间:2024/05/16 11:21
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
分析:其实之前也做过类似题,之前是一个正方形矩阵,现在换成长宽不一定相等的了。定义四个变量固定打印的对角线的角,然后依次打印就可以了。要注意过程中不能重复打印和缺少元素。
class Solution {public: vector<int> printMatrix(vector<vector<int> > matrix) { vector<int>ret;int m=matrix.size(); int n=matrix[0].size(); if(m==0||n==0) return ret; int row1=0; int row2=m-1; int col1=0; int col2=n-1; while(row1<=row2&&col1<=col2){ for(int i=col1;i<=col2;i++){ ret.push_back(matrix[row1][i]); } for(int i=row1+1;i<=row2;i++){ ret.push_back(matrix[i][col2]); } if(row2!=row1){ for(int i=col2-1;i>=col1;i--){ ret.push_back(matrix[row2][i]); } } if(col2!=col1){ for(int i=row2-1;i>row1;i--){ ret.push_back(matrix[i][col1]); } } row1++; row2--; col1++; col2--; } return ret; }};
0 0
- 【剑指offer】顺时针打印矩阵
- 剑指offer--顺时针打印矩阵
- 剑指offer--顺时针打印矩阵
- 剑指offer 顺时针打印矩阵
- 剑指offer:顺时针打印矩阵
- 《剑指offer》顺时针打印矩阵
- 剑指offer-顺时针打印矩阵
- 剑指offer 顺时针打印矩阵
- 剑指offer:顺时针打印矩阵
- 剑指offer-顺时针打印矩阵
- 剑指offer 顺时针打印矩阵
- 剑指offer:顺时针打印矩阵
- [剑指offer]顺时针打印矩阵
- 《剑指offer》-顺时针打印矩阵
- 【剑指offer】顺时针打印矩阵
- 剑指offer|顺时针打印矩阵
- 《剑指offer》顺时针打印矩阵
- 剑指Offer:顺时针打印矩阵
- 【JavaEE框架】MyBatis基础使用
- 公告:CSDN博客频道自定义摘要、图片水印、热门标签功能正式上线!
- android source bluetooth
- oracle字符集的问题
- 将中缀表达式转换成后缀表达式并计算
- [剑指offer]顺时针打印矩阵
- iOS中的单例模式
- Android 自定义打印log
- 文章标题
- iOS开发之如何跳到系统设置里的各种设置界面
- CSDN博客去图片水印
- mymemcpy的实现
- meta标签 搜索引擎优化 SEO
- nyoj 667 Biggest Number 搜索 减枝 dfs bfs