您的位置:首页 > 职场人生

[剑指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.

对于只有一行、一列的情况特殊考虑;对边界条件设置清除,细心一点即可。

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]);
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: