zoukankan      html  css  js  c++  java
  • 剑指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.

    代码:

     1 class Solution {
     2 public:
     3     vector<int> printMatrix(vector<vector<int>> matrix) {
     4         int row=matrix.size();
     5         int col=matrix[0].size();
     6         vector<int> result;
     7         if(row==0||col==0)
     8             return result;
     9         int left=0,right=col-1,top=0,btm=row-1;
    10         while(left<=right&&top<=btm)
    11             {
    12             for(int i=left;i<=right;i++)
    13                 result.push_back(matrix[top][i]);
    14             if(top<btm)
    15                 for(int i=top+1;i<=btm;i++)
    16                     result.push_back(matrix[i][right]);
    17             if(top<btm&&left<right)
    18                 for(int i=right-1;i>=left;i--)
    19                     result.push_back(matrix[btm][i]);
    20             if(top+1<btm&&left<right)
    21                 for(int i=btm-1;i>=top+1;i--)
    22                     result.push_back(matrix[i][left]);
    23             left++;right--;top++;btm--;
    24         }
    25         return result;
    26     }
    27 };

    我的笔记:根据数组规律,可设四个位置标点,并进行四种循环;(1)从左至右遍历;(2)从上至下遍历;(3)从右至左遍历;(4)从下至上遍历。四种循环后将四个位置标点逐个更改,并再每次循环之前判断标点位置是否过界。

  • 相关阅读:
    WINDOWPOS结构
    HTML 4.01 符号实体
    建立窗体时所响应的消息
    如何用正确的方法来写出质量好的软件的75条体会
    Onload加载多个方法函数
    UML中的一些概念
    aop应用范围
    如何成为“10倍效率”开发者
    网页引入taglibs
    XML编程—CRUD
  • 原文地址:https://www.cnblogs.com/john1015/p/12952224.html
Copyright © 2011-2022 走看看