zoukankan      html  css  js  c++  java
  • 【leetcode】Spiral Matrix II (middle)

    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    For example,
    Given n = 3,

    You should return the following matrix:

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

    思路:

    我是直接套用了Spiral Matrix 的代码

    class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            vector<vector<int>> ans(n, vector<int>(n,0));
    
            int num = 1;
            for(int i = 0; i < (n + 1) / 2; i++)
            {
                //行 ----->
                for(int j = i; j < n - i; j++)
                    ans[i][j] = num++;
                //列 向下
                for(int j = i + 1; j < n - i; j++)
                    ans[j][n - 1 - i] = num++;
                //行 <-----------
                if(n - i - 1 <= i) //列号 一定要比向左时的列号小 防止重复
                    break;
                for(int j = n - i - 2; j >= i; j--)
                    ans[n - i - 1][j] = num++;
                //列 向上
                if(i >= n - 1 - i) //行号 一定要比向下时的行号大 防止重复
                    break;
                for(int j = n - i - 2; j >= i + 1; j--)
                    ans[j][i] = num++;
            }
            return ans;
        }
    };

    另一种写法的:

    class Solution {
        public:
            vector<vector<int> > generateMatrix(int n) {
                vector<vector<int> > ret( n, vector<int>(n) );
                int k = 1, i = 0;
                while( k <= n * n )
                {
                    int j = i;
                        // four steps
                    while( j < n - i )             // 1. horizonal, left to right
                        ret[i][j++] = k++;
                    j = i + 1;
                    while( j < n - i )             // 2. vertical, top to bottom
                        ret[j++][n-i-1] = k++;
                    j = n - i - 2;
                    while( j > i )                  // 3. horizonal, right to left 
                        ret[n-i-1][j--] = k++;
                    j = n - i - 1;
                    while( j > i )                  // 4. vertical, bottom to  top 
                        ret[j--][i] = k++;
                    i++;      // next loop
                }
                return ret;
            }
        };
  • 相关阅读:
    3月3日(6) Climbing Stairs
    testNG 预期异常、忽略测试、超时测试
    testNG 常用的注解
    testNG 下载安装
    selenium 执行js代码
    selenium 时间等待的方法
    selenium 文件上传
    selenium 键盘鼠标模拟
    selenium 窗口的切换
    selemiun 下拉菜单、复选框、弹框定位识别
  • 原文地址:https://www.cnblogs.com/dplearning/p/4347484.html
Copyright © 2011-2022 走看看