zoukankan      html  css  js  c++  java
  • 顺时针打印矩阵

    题目

     输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵,则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

       把矩阵看成由若干个顺时针方向的圈组成,循环打印矩阵中的每个圈,每次循环打印一个圈。

      打印一圈通常分为四步,设置四个变量left,right,top,botm,用于表示圈的方位,每一步根据起始坐标和终止坐标循环打印。

    • 第一步从左到右打印一行,每圈至少有一步,不需加限制条件
    • 第二步从上到下打印一列,至少有两行,所以top<botm
    • 第三步从右到左打印一行,至少有两行,两列,所以top<botm,left<right
    • 第四步从下到上打印一列,至少有三行,两列,所以top+1<botm,left<right

    注意:最后一圈有可能不需要四步,有可能只有一行,只有一列,只有一个数字,因此我们要仔细分析打印每一步的前提条件

    class Solution {
    public:
        vector<int> printMatrix(vector<vector<int> > matrix) {
            if(matrix.empty())
                return {};
            
            vector<int> res;
            int top=0,bottom=matrix.size()-1;
            int left=0,right=matrix[0].size()-1;
            
            while(top<=bottom&&left<=right)
            {
                for(int i=left;i<=right;++i)
                    res.push_back(matrix[top][i]);
                
                if(top<bottom)
                for(int i=top+1;i<=bottom;++i)
                    res.push_back(matrix[i][right]);
                
                if(top<bottom&&left<right)
                for(int i=right-1;i>=left;--i)
                    res.push_back(matrix[bottom][i]);
                
                if(top+1<bottom&&left<right)
                for(int i=bottom-1;i>top;--i)
                    res.push_back(matrix[i][left]);
                
                ++top,--bottom,++left,--right;
            }
            return res;
        }
    };
  • 相关阅读:
    Windows API—CreateEvent—创建事件
    C++的注册和回调
    Python内置模块-logging
    使用 C++ 处理 JSON 数据交换格式
    Python生成器
    5.Spring-Boot缓存数据之Redis
    6.Spring-Boot项目发布到独立的tomcat中
    7.Spring-Boot自定义Banner
    8.Spring-Boot之SpringJdbcTemplate整合Freemarker
    9.Spring-Boot之Mybatis-LogBack-Freemarker
  • 原文地址:https://www.cnblogs.com/tianzeng/p/10181811.html
Copyright © 2011-2022 走看看