zoukankan      html  css  js  c++  java
  • Spiral Matrix II

    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 ]
    ]
    

     分析: 典型的题目 注意二维数组遍历的方式,“一圈圈”来遍历比较直接

    class Solution {
    public:
        vector<vector<int>> generateMatrix(int n) {
            vector<vector<int>> matrix(n, vector<int>(n,0));
            int len;
            int cnt=1;
            int x=0,y=0;
           
            for(int i=0; i*2<n; i++){
                cout << "i = "<< i<<endl;
                // start point (i,i)
                len = n-i*2;
                x = y =i;
                if(len == 1)
                    matrix[x][y] =cnt;
                // go right
                for(int j=0; j<len-1; j++){
                    matrix[x][y++] = cnt;
                    cnt++;
                }
                
                // go down
                for(int j=0; j<len-1; j++){
                    matrix[x++][y] = cnt;
                    cnt++;
                }
                
                // go left
                for(int j=0; j<len-1; j++){
                    matrix[x][y--] = cnt;
                    cnt++;
                }
                
                // go up
                for(int j=0; j<len-1; j++){
                    matrix[x--][y] = cnt;
                    cnt++;
                }
            }
            return matrix;
        }
    };

    PS: 寒假开始, 每日重点就是leetcode, 两个星期看看能做多少

  • 相关阅读:
    C++输入问题探究
    剑指offer自学系列(一)
    一道算法题加深我对C++中map函数的理解
    数据结构和算法自学之排序算法(一)
    pyqt5_01_流程走通
    最新谷歌驱动对照表
    移动端测试
    selenium封装
    request封装
    MD5自定义加密
  • 原文地址:https://www.cnblogs.com/willwu/p/6347805.html
Copyright © 2011-2022 走看看