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

    题目描述

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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.
    思路:设置4个标记,分别为上下左右。每次输出完都更新标记,while的循环条件一定要left <= right &&bottom>=top  ,要加=,因为可能矩阵为只有1行或只有一列。内部的循环条件也是。
    代码:
    class Solution {
    public:
        vector<int> printMatrix(vector<vector<int> > matrix) {
            int row = matrix.size();
            int column = matrix[0].size();
            vector<int> sum;
            if(row == 0 || column == 0)
                return sum;
            int left = 0;
            int right = column-1;
            int top = 0;
            int bottom = row-1;
            while(top <= bottom && right >= left)
            {
                for(int i  = left; i <= right;i++)
                    sum.push_back(matrix[top][i]);
                for(int i = top+1; i <= bottom; i++)
                    sum.push_back(matrix[i][right]);
                if(top != bottom)
                for(int i = right-1; i >= left;i--)
                    sum.push_back(matrix[bottom][i]);
                if(right != left)
                for(int i = bottom-1;i > top;i--)
                    sum.push_back(matrix[i][left]);
                top++;bottom--;left++;right--;
            }
            return sum;
        }
    };
  • 相关阅读:
    第三章 Jenkins参数及web项目
    第二章 Jenkins的详细介绍
    第一章 Git+Gitlab介绍和安装
    第二章 Centos7下Airflow2.1.0安装
    第一章 Airflow基本原理
    第五章 Pinpoint-Apm常见报错
    第四章 Docker方式安装 Pinpoint
    数论练习
    CF练习
    矩阵乘法
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/9094484.html
Copyright © 2011-2022 走看看