顺时针打印矩阵

题目描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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;
    }
};

posted on 2017-03-12 10:38  jec  阅读(139)  评论(0编辑  收藏  举报

导航