剑指Offer(29):顺时针打印矩阵

题目
  • 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每个数字,例如,如果输入如下矩阵:

在这里插入图片描述


则依次打印出数组:1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10。

  1. 思路

    将结果存放在vector 数组中,从左到右,再从上到下,再从右到左,最后从下到上遍历。

  2. 思考:

  • 遍历停止的标志是什么
  • 边界必须非常清晰的控制好! 考察边界控制能力!

代码:

vector<int> printMatrix(vector<vector<int> > matrix)
{
    vector<int> result;
    int rows = matrix.size();
    int cols = matrix[0].size();

    if(rows == 0 && cols == 0)
    {
        return result;
    }
    int left = 0, right = cols - 1, top = 0, bottom = rows - 1;

    while(left <= right && top <= bottom)
    {
        //from left to right
        for(int i = left; i <= right; ++i)
        {
            result.push_back(matrix[top][i]);
        }
        //from top to bottom
        for(int i = top + 1; i <= bottom; ++i)
        {
            result.push_back(matrix[i][right]);
        }
        //from right to left
        if(top != bottom)
        {
            for(int i = right - 1; i >=left; --i)
            {
                result.push_back(matrix[bottom][i]);
            }
        }
        //from bottom to top
        if(left != right)
        {
            for(int i = bottom -1; i > top; --i)
            {
                result.push_back(matrix[i][left]);
            }
        }
        left++, top++, right--, bottom;
    }
    return result;
}
  • 代码思路比较清晰,要注意特殊情况,例如最后只剩下一束或一横可走,那么,只剩一下一束,则不用再走from bottom to top!!! 而这剩下一束的标志是,right == bottom!!! 同理,只剩下一横,则不用再走from right to left!!! 而剩下 一横的标志是 top= bottom!!!!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值