Acwing40. 顺时针打印矩阵

地址 https://www.acwing.com/solution/acwing/content/3623/

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

样例

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

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

算法1
顺时针 就是按照右 下 左 上 次序依次打印
并且建立同matrix同样大小的二维数组 记录该点是否已经访问 如果访问了则不能再进
在依次打印的过程中,如果遇到坐标不符合标准则右转90度,继续打印,直到一步都不能走了 则退出循环

C++ 代码

class Solution {
public:
    vector<int> result;
    vector<vector<bool>> matrixFlag;
    int upd = 0; int downd = 1; int leftd = 2; int rightd = 3;
    int movex[4] = { -1,1,0,0 };
    int movey[4] = { 0,0,-1,1 };

    bool PrintInner(int& x, int& y, const vector<vector<int> >& matrix,int direct)
    {
        if (x < 0 || y < 0 || x >= matrix.size() || y >= matrix[0].size())
            return false;
        if (matrixFlag[x][y] == false)
            return false;
        int xcopy = x; int ycopy = y;
        while (ycopy >= 0 && xcopy >= 0 && xcopy < matrix.size() && ycopy < matrix[0].size() && matrixFlag[xcopy][ycopy] == true) {
            result.push_back(matrix[xcopy][ycopy]);
            matrixFlag[xcopy][ycopy] = false;
            y = ycopy; x = xcopy;
            xcopy += movex[direct];
            ycopy += movey[direct];
        }

        return true;
    }


    vector<int> printMatrix(vector<vector<int> > matrix) {
        if (matrix.empty() || matrix[0].empty())  return result;
        int n = matrix.size();
        int m = matrix[0].size();

        matrixFlag = vector<vector<bool>>(n,vector<bool>(m,true));
        int x = 0; int y = 0;

        while (1) {
            if (PrintInner(x, y, matrix, rightd) == false) break;
            x += movex[downd]; y += movey[downd];

            if (PrintInner(x, y, matrix, downd) == false) break;
            x += movex[leftd]; y += movey[leftd];

            if (PrintInner(x, y, matrix, leftd) == false) break;
            x += movex[upd]; y += movey[upd];

            if (PrintInner(x, y, matrix, upd) == false) break;
            x += movex[rightd]; y += movey[rightd];
        }
        return result;
    }
};

作者:defddr
链接:https://www.acwing.com/solution/acwing/content/3623/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
作 者: itdef
欢迎转帖 请保持文本完整并注明出处
技术博客 http://www.cnblogs.com/itdef/
B站算法视频题解
https://space.bilibili.com/18508846
qq 151435887
gitee https://gitee.com/def/
欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
如果觉得不错,欢迎点赞,你的鼓励就是我的动力
阿里打赏 微信打赏
原文地址:https://www.cnblogs.com/itdef/p/11327603.html