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.

    代码

    class Solution {
    public:
        vector<int> printMatrix(vector<vector<int> > matrix) {
    		vector<int> ans;
            if (matrix.size() > 0) {
            	int x1 = 0, y1 = 0, x2 = matrix.size() - 1, y2 = matrix[0].size() - 1;
    
                while (true) {
                    for (int i = y1; i <= y2; ++i) {//打印矩形的最上一行
                        ans.push_back(matrix[x1][i]);
                    }
                    ++x1;
                    if (x1 > x2) {
                        break;
                    }
                    for (int i = x1; i <= x2; ++i) {//打印矩形的右边行
                        ans.push_back(matrix[i][y2]);
                    }
                    --y2;
                    if (y1 > y2) {
                        break;
                    }
                    for (int i = y2; i >= y1; --i) {//打印矩形的最下行
                        ans.push_back(matrix[x2][i]);
                    }
                    --x2;
                    if (x1 > x2) {
                        break;
                    }
                    for (int i = x2; i >= x1; --i) {//打印矩形的左边行
                        ans.push_back(matrix[i][y1]);
                    }
                    ++y1;
                    if (y1 > y2) {
                        break;
                    }
                }
            }
            return ans;
        }
    };
    
  • 相关阅读:
    hdu 5902 Seam Carving
    hdu 5091 Beam Cannon
    hdu 1542 Atlantis
    hdu 2196 Computer
    第一个爬虫和测试
    排球比赛规则
    第十周博客作业
    科学计算可视化
    用matplotlib绘制图像
    面对对象学习
  • 原文地址:https://www.cnblogs.com/jecyhw/p/6537164.html
Copyright © 2011-2022 走看看