剑指 Offer 29. 顺时针打印矩阵

顺时针打印矩阵


题目链接: 顺时针打印矩阵

有关题目

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:

输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:

输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:

0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

题解

法一:模拟

思路:
模拟打印矩阵的路径。
初始位置是矩阵的左上角,初始方向是向右,
当路径超出界限或者进入之前访问过的位置时,
顺时针旋转,进入下一个方向
class Solution {
private:
    static constexpr int directions[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
    //创建四个只在当前使用的源文件使用的方向数组
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};//特判返回空矩阵
        }
        int m = matrix.size(), n =  matrix[0].size();
        vector<vector<bool>> visited(m,vector<bool>(n));
        int total = m * n;
        vector<int> order(total);

        int row = 0, col = 0;
        int directionIndex = 0;
        for (int i = 0; i < total; i++){
            order[i] = matrix[row][col];
            visited[row][col] = true;
            int nextRow = row + directions[directionIndex][0], nextCol = col + directions[directionIndex][1];
            if (nextRow < 0 || nextRow >= m || nextCol < 0 || nextCol >= n || visited[nextRow][nextCol]){//注意这边是下一个方向
                directionIndex = (directionIndex + 1) % 4;//每四次方向一循环
            }
            row += directions[directionIndex][0];
            col += directions[directionIndex][1];
        }
        return order;
    }
};

在这里插入图片描述

方法二:按层模拟

思路:
按照顺时针从最外层的左上角元素开始遍历,一直到最里层的元素

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0 || matrix[0].size() == 0) {
            return {};//特判返回空矩阵
        }
        int m = matrix.size(), n = matrix[0].size();
        vector<int> order;
        int left = 0, right = n - 1, top = 0, bottom = m - 1;
        while(left <= right && top <= bottom){
            for(int i = left; i <= right; ++i){
                order.push_back(matrix[top][i]);
            }
            for(int j = top + 1; j <= bottom; ++j){
                order.push_back(matrix[j][right]);
            }
            if (left < right && top < bottom){//即未到最里层
                for (int i = right - 1; i > left; --i){
                    order.push_back(matrix[bottom][i]);
                }
                for (int j = bottom; j > top; --j){
                    order.push_back(matrix[j][left]);
                }
            }
            left++;
            right--;
            top++;
            bottom--;
        }
        return order;
    }
};

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值