zoukankan      html  css  js  c++  java
  • LeetCode_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) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            vector<vector<int>> res(n,vector<int>(n));
            
            int lays = (n+1)/2;
            bool single = n%2;
            int num = 1;
            for(int lay = 0; lay < lays; lay ++){
            
                int topRow = lay;
                int rightColumn = n - 1 - lay;
                
                //process the top
                for(int i = lay; i <= rightColumn; i++)
                      res[topRow][i] = num++;
                      
                //process the right Column
                for(int i = lay+1; i <= rightColumn ;i++)
                      res[i][rightColumn] = num++;
                      
                if(lay == lays -1 && single )
                        continue;
                        
                //process the bottom 
                for(int i = rightColumn - 1; i>= lay; i--)
                      res[rightColumn][i] = num++;
                      
                for(int i = rightColumn - 1; i> lay ;i--)
                     res[i][lay] = num++;
            
            }
            
            return res;
        }
    };
  • 相关阅读:
    keyCode对照表
    WebApi的前端调用
    AJAX get和post请求
    Linq中常用语法
    MVC三种分页方法
    常用DBhelper封装方法
    ASP.NET MVC 导入Excel文件(完整版)
    Razor语法2
    MVC之路由规则 (自定义,约束,debug)
    MVC
  • 原文地址:https://www.cnblogs.com/graph/p/3233407.html
Copyright © 2011-2022 走看看