AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 40. 顺时针打印矩阵    原题链接    中等

作者: 作者的头像   ZhCoding ,  2019-09-10 17:51:51 ,  所有人可见 ,  阅读 912


0


题目描述

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

样例

输入:
[
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9,10,11,12]
]

输出:[1,2,3,4,8,12,11,10,9,5,6,7]

递归算法

递归按顺时针访问矩阵的元素并保存在结果中。

时间复杂度O(mn)

C++ 代码

class Solution {
public:

    int dx[4] = {0, 1, 0, -1}, dy[4] = {1, 0, -1, 0};

    void visit(vector<int>& res, vector<vector<bool>>& st, vector<vector<int>>& matrix, int x, int y, int d){
        res.push_back(matrix[x][y]);
        st[x][y] = true;
        int cnt = 0;
        for(int i = d; cnt < 4; i = (i + 1)%4){ // 将过来的方向作为本次的起始方向
            int xx = x + dx[i], yy = y + dy[i];
            if(xx >= 0 && xx < matrix.size() && yy >= 0 && yy < matrix[0].size() && !st[xx][yy]){
                visit(res, st, matrix, xx, yy, i);
            }
            cnt ++;
        }
        return;
    }

    vector<int> printMatrix(vector<vector<int> > matrix) {

        if(!matrix.size() || !matrix[0].size()) return {};

        vector<int> res;
        vector<vector<bool>> st(matrix.size(), (vector<bool>(matrix[0].size())));

        visit(res, st, matrix, 0, 0, 0);

        return res;
    }
};

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息