zoukankan      html  css  js  c++  java
  • 54.Spiral Matrix

    给定一个二维数组,将数组中的元素按照螺旋顺序输出,顺时针螺旋。

    Input:
    [
    [ 1, 2, 3 ],
    [ 4, 5, 6 ],
    [ 7, 8, 9 ]
    ]
    Output: [1,2,3,6,9,8,7,4,5]

    思路:
    使用迷宫遍历,设定寻路的方向,当碰壁了,就换到下一个方向,但是要将已经走过的点标记出来,使用 0 标记。

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            if (matrix.empty() || matrix[0].size() == 0) return {};
            vector<int> res;
            int m = matrix.size(), n = matrix[0].size(), i = 0, j = 0, idx = 0;
            int c[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
            for (int k = 0; k < m * n; k++) {
                res.push_back(matrix[i][j]);
                matrix[i][j] = 0;
                int x = i + c[idx][0];
                int y = j + c[idx][1];
                if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] == 0) {
                    idx = (idx + 1) % 4;
                    x = i + c[idx][0];
                    y = j + c[idx][1];
                }
                i = x; j = y;
            }
            return res;
        }
    };

    二、使用坐标顺序读取的方式,设定上下左右的坐标,每次读完就更新坐标。如:二维数组为 m*n的数组,则: up = 0, down = m-1, left = 0, right = n-1; 每次读完一个顺序,就将对应的 up +1 , right -1, down -1 ,left +1, 并随时判断是否满足条件: up <= down, left <= right 的要求。

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
            if (matrix.empty() || matrix[0].size() == 0) return {};
            vector<int> res;
            int m = matrix.size(), n = matrix[0].size();
            int up = 0, down = m - 1, left = 0, right = n - 1;
            while (true) {
                for (int j = left; j <= right; j++) res.push_back(matrix[up][j]);
                if (++up > down) break;
                for (int j = up; j <= down; j++) res.push_back(matrix[j][right]);
                if (--right < left) break;
                for (int j = right; j >= left; j--) res.push_back(matrix[down][j]);
                if (--down < up) break;
                for (int j = down; j >= up; j--) res.push_back(matrix[j][left]);
                if (++left > right) break;
            }
            return res;
        }
    };
  • 相关阅读:
    python3.4 + pycharm 环境安装 + pycharm使用
    ddt源码修改:HtmlTestRunner报告依据接口名显示用例名字
    re模块
    LeetCode Weekly Contest 12
    求解强连通分量
    几道题-找规律-记录并查找
    欧几里德算法
    树上二分
    几道题-博弈
    随便写一些东西-缩边
  • 原文地址:https://www.cnblogs.com/luo-c/p/12984529.html
Copyright © 2011-2022 走看看