zoukankan      html  css  js  c++  java
  • 剑指Offer-顺时针打印矩阵

    题目:

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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个变量:left = 0;right = col-1;top = 0;bottom = row-1。然后按照从左向后、从上向下、从右向左、从下向上的顺序打印即可。需要注意的是,在打印从右向左时,需要判断top是否等于bottom;若相等,则不必打印该行;在打印从下向上时,需要判断left是否等于right,若相等,则不必打印该列。

    代码:

     1 class Solution {
     2 public:
     3     vector<int> printMatrix(vector<vector<int> > matrix) {
     4         int bottom = matrix.size() - 1;
     5         int right = matrix[0].size() - 1;
     6         int left = 0;
     7         int top = 0;
     8         vector<int> result;
     9         while (left <= right && top <= bottom) {
    10             //从左向右
    11             for (int i = left; i <= right; i++)
    12                 result.push_back(matrix[top][i]);
    13             //从上向下
    14             for (int i = top + 1; i <= bottom; i++)
    15                 result.push_back(matrix[i][right]);
    16             if (top != bottom)
    17                 //从右向左
    18                 for (int i = right - 1; i >= left; i--)
    19                     result.push_back(matrix[bottom][i]);
    20             if (left != right)
    21                 //从下向上
    22                 for (int i = bottom - 1; i >= top + 1; i--)
    23                     result.push_back(matrix[i][left]);
    24             left++;
    25             right--;
    26             top++;
    27             bottom--;
    28         }
    29         return result;
    30     }
    31 };
    View Code
  • 相关阅读:
    一个可以用的Lua的Class函数
    写一个可以用的Lua打印Table的函数
    关于C#的接口的碎碎念
    C#中接口是值类型还是引用类型?
    Effective C++笔记_条款31将文件间的编译依存关系降至最低
    Effective C++ 阅读笔记_条款27 尽量少做转型动作
    Flask--开发全套
    python之元类
    Django之模板层
    go打开文件
  • 原文地址:https://www.cnblogs.com/sindy/p/7391273.html
Copyright © 2011-2022 走看看