[剑指offer]面试题20:顺时针打印矩阵
2017-10-02 10:09
429 查看
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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 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> res; if(matrix.empty()) return res; int start_row = 0; int start_col = 0; int end_row = matrix.size() - 1; int end_col = matrix[0].size() - 1; while(start_row <= end_row && start_col <= end_col){ printOneCycle(res, matrix, start_row++, start_col++, end_row--, end_col--); } return res; } // 索引从0开始,一圈的左上角(start_row, start_col),一圈的右下角(end_row, end_col) void printOneCycle(vector<int>& res, vector<vector<int>>& matrix, int start_row, int start_col, int end_row, int end_col){ // 处理只有一行的特殊情况 if(start_row == end_row){ for(int i = start_col; i <= end_col; ++i) res.push_back(matrix[start_row][i]); return; } // 处理只有一列的特殊情况 if(start_col == end_col){ for(int i = start_row; i <= end_row; ++i) res.push_back(matrix[i][start_col]); return; } // 正常打印一圈的情况 for(int i = start_col; i <= end_col; ++i){ res.push_back(matrix[start_row][i]); } for(int i = start_row + 1; i <= end_row; ++i){ res.push_back(matrix[i][end_col]); } for(int i = end_col - 1; i >= start_col; --i){ res.push_back(matrix[end_row][i]); } for(int i = end_row - 1; i > start_row; --i){ res.push_back(matrix[i][start_col]); } } };
相关文章推荐
- 【面试题】剑指offer20--顺时针打印一个矩阵的数字
- 剑指offer面试题20-顺时针打印矩阵
- 【剑指offer】面试题20:顺时针打印矩阵
- 剑指Offer面试题20(Java版):顺时针打印矩阵
- 剑指offer-面试题 20:顺时针打印矩阵
- 剑指offer-4-面试题20:顺时针打印矩阵(画图使抽象问题形象化)
- 剑指offer 面试题20—顺时针打印矩阵
- 剑指offer——面试题20:顺时针打印矩阵
- 剑指offer--面试题20:顺时针打印矩阵--Java实现
- 剑指offer面试题[20]-顺时针打印矩阵
- 剑指Offer之面试题20:顺时针打印矩阵
- Java 剑指offer_面试题20_顺时针打印矩阵(思路在一步步分解之中)
- 剑指offer-面试题20.顺时针打印矩阵
- 剑指offer——面试题20:顺时针打印矩阵
- 【剑指Offer】面试题20:顺时针打印矩阵
- [剑指offer][面试题20]顺时针打印矩阵
- 剑指offer_面试题20_顺时针打印矩阵(思路在一步步分解之中)
- 剑指Offer----面试题20:顺时针打印矩阵
- 剑指offer-面试题20.顺时针打印矩阵
- 剑指offer-面试题20 顺时针打印矩阵