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 };
  • 相关阅读:
    洛谷 P1037 产生数
    【bzoj】 1070: [SCOI2007]修车
    【bzoj】 1066: [SCOI2007]蜥蜴 (网络流)
    开发环境搭建
    数据库设计
    sql优化实例(用左连接)
    泛型T和通配符?的区别
    Nginx配置优化
    Tomcat优化
    Nginx反向代理配置
  • 原文地址:https://www.cnblogs.com/gousheng/p/9373514.html
Copyright © 2011-2022 走看看