首页 > 代码库 > 顺时针打印矩阵

顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 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) {
        if (matrix.empty()) {
            return matrix[0];
        }
        int row = static_cast<int>(matrix.size()) ;
        int column = static_cast<int>(matrix[0].size()) ;
        int start = 0;
        vector<int> result;
        result.clear();
         
        while (column > start*2 && row > start*2) {
            int endX = column - 1 - start;
            int endY = row - 1 - start;
            //从左到右打印一行
            for (int i=start; i<=endX; i++) {
                result.push_back(matrix[start][i]);
            }
            //从上到下打印一行
            if (start <endY) {
                for (int i=start+1; i<=endY; i++) {
                    result.push_back(matrix[i][endX]);
                }
            }
            //从右到左打印一行
            if (start < endX && start < endY) {
                for (int i=endX-1; i>=start; i--) {
                    result.push_back(matrix[endY][i]);
                }
            }
            //从下到上打印一行
            if (start<endX && start<endY-1) {
                for (int i=endY-1; i>=start+1; i--) {
                    result.push_back(matrix[i][start]);
                }
            }
            start++;
        }
        return result;
    }
};

  

 

另外一种思路:

 

用旋转魔法的方式,一直取出第一行;
例如
1 2 3
4 5 6
7 8 9
输出并删除第一行后,变为
4 5 6
7 8 9
再进行一次逆时针旋转,就变成:
6 9
5 8
4 7
继续重复上述操作即可。

顺时针打印矩阵