• 59.Spiral Matrix II


    给定一个正整数,要求,输出一个螺旋状的 n*n 二维矩阵,元素从 1 ~ n*n 的值按螺旋顺序排列。

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


    思路:
    一、此题跟54题十分类似,基本就是在54题的基础上稍微变换。使用坐标顺序写入的方式,设定上下左右的坐标,每次写完就更新坐标。如:二维数组为 n*n的数组,则: up = 0, down = n-1, left = 0, right = n-1; 每次读完一个顺序,就将对应的 up +1 , right -1, down -1 ,left +1, 并随时判断是否满足条件: up <= down, left <= right 的要求。

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> res(n, vector<int>(n));
            int up = 0, down = n - 1, left = 0, right = n - 1, idx = 1;
            while (true) {
                for (int i = left; i <= right; i++) res[up][i] = idx++;
                if (++up > down) break;
                for (int i = up; i <= down; i++) res[i][right] = idx++;
                if (--right < left) break;
                for (int i = right; i >= left; i--) res[down][i] = idx++;
                if (--down < up) break;
                for (int i = down; i >= up; i--) res[i][left] = idx++;
                if (++left > right) break;
            }
            return res;
        }
    };

    二、使用迷宫遍历,先将 n*n 的二维数组元素都设为 0 ,设定寻路的方向,边走边写入值,当碰壁了,或者元素的值大于0,就换到下一个方向。

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> res(n, vector<int>(n));
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) res[i][j] = 0;
            }
            int a[4][2] = { {0,1},{1,0},{0,-1},{-1,0} };
            int i = 0, j = 0, idx = 0, count = 1;
            for (int k = 0; k < n * n; k++) {
                res[i][j] = count++;
                int x = i + a[idx][0];
                int y = j + a[idx][1];
                if (x < 0 || x >= n || y < 0 || y >= n || res[x][y] > 0) {
                    idx = (idx + 1) % 4;
                    x = i + a[idx][0];
                    y = j + a[idx][1];
                }
                i = x; j = y;
            }
            return res;
        }
    };
  • 相关阅读:
    Spark Streaming
    RDD转换DataFrame
    Spark学习笔记之-Spark远程调试
    Spark集群模式&Spark程序提交
    spark-submit的参数名称解析
    Scala java maven开发环境搭建
    git报错之index.lock
    mongodb导出数据表命令之mongoexport
    用casperjs模拟登录,支持多个账户登录
    关于casperjs的wait方法的执行顺序
  • 原文地址:https://www.cnblogs.com/luo-c/p/12990018.html
Copyright © 2020-2023  润新知