剑指offer:顺时针打印矩阵

题目描述:

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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.

 

解题思路:

这题之前刷leetcode时遇到过。用四个指针来维护矩阵的上下左右边界,每输出完一行或一列就改动对应指针,使得矩阵的搜索范围缩写。

注意,每次更新完边界时,需要进行一次边界判断,防止重复扫描。

 

代码:

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        vector<int> res;
        if(matrix.size()==0)
            return res;
        int row_t = 0;
        int row_b = matrix.size()-1;
        int col_l = 0;
        int col_r = matrix[row_t].size()-1;
        while(row_t<=row_b && col_l<=col_r)
        {
            for(int i = col_l; i<=col_r; i++)
            {
                res.push_back(matrix[row_t][i]);
            }
            row_t++;
            if(row_t>row_b)
                break;
            for(int i = row_t; i<=row_b; i++)
            {
                res.push_back(matrix[i][col_r]);
            }
            col_r--;
            if(col_r<col_l)
                break;
            for(int i = col_r; i>=col_l; i--)
            {
                res.push_back(matrix[row_b][i]);
            }
            row_b--;
            if(row_b<row_t)
                break;
            for(int i = row_b; i>=row_t; i--)
            {
                res.push_back(matrix[i][col_l]);
            }
            col_l++;
            if(col_l>col_r)
                break;
        }
        return res;
    }
};

 

posted @ 2019-03-25 21:53  Fzu_LJ  阅读(144)  评论(0编辑  收藏  举报