19.顺时针打印矩阵

2019-08-12  本文已影响0人  iwtbam

题目描述

解题思路

AC代码

class Solution {
public:
    vector<int> printMatrix(vector<vector<int> > matrix) {
        int rows = matrix.size();
        int cols = matrix[0].size();

                vector<vector<int>> label(rows, vector<int>(cols, 0));
        //vector<vector<int>> label = {rows, vector<int>(cols, 0)}; 其实我更喜欢这样写可惜牛客网的编译器不支持C++17
        int dx[] = { 1, 0, -1, 0 };
        int dy[] = { 0, 1, 0 ,-1 };
        int dir = 0;
        int curx = 0;
        int cury = 0;

        vector<int> iv;
        int total = rows * cols;

        iv.push_back(matrix[0][0]);
        label[0][0] = 1;

        while (iv.size() < total) {

            int nextx = curx + dx[dir];
            int nexty = cury + dy[dir];


            if (nextx >= 0 && nextx < cols && nexty >= 0 && nexty < rows&& !label[nexty][nextx]) {
                curx = nextx;
                cury = nexty;
                label[nexty][nextx] = 1;
                iv.push_back(matrix[cury][curx]);
            }
            else {
                dir = (dir + 1) % 4;
            }

        }

        return iv;
    }
};
上一篇下一篇

猜你喜欢

热点阅读