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

    题目描述

    输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下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 x = matrix.size();
     5         int y = matrix[0].size();
     6         int left = 0, top = 0, right = y - 1, bottom = x - 1;
     7         vector<int> res;
     8         while (left <= right && top <= bottom) {
     9             for (int i = left; i <= right; i++) {
    10                 res.push_back(matrix[top][i]);
    11             }
    12             for (int i = top + 1; i <= bottom; i++) {
    13                 res.push_back(matrix[i][right]);
    14             }
    15             if (top != bottom) {
    16                 for (int i = right - 1; i >= left; i--) {
    17                     res.push_back(matrix[bottom][i]);
    18                 }
    19             }
    20             if (left != right) {
    21                 for (int i = bottom - 1; i > top; i--) {
    22                     res.push_back(matrix[i][left]);
    23                 }
    24             }
    25             
    26             left++, right--, top++, bottom--;
    27         }
    28         return res;
    29     }
    30 };
  • 相关阅读:
    js简单地发送一个请求
    浏览器缓存知识归纳
    文本选择问题: css & js
    闭包和重写函数 返回IE浏览器版本号
    新项目启动 考虑问题
    Angular 单元格合并
    pointer-events 使用场景
    移动开发 新建空白页面
    CSS Tip
    垂直居中方法
  • 原文地址:https://www.cnblogs.com/gousheng/p/9373514.html
Copyright © 2011-2022 走看看