• 【leetcode】Spiral Matrix II


    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 ]
    ]
    
     
    与Spiral Matrix类似:
     
     1 class Solution {
     2 public:
     3     vector<vector<int> > generateMatrix(int n) {
     4        
     5         int x1=0;
     6         int y1=0;
     7         int x2=n-1;
     8         int y2=n-1;
     9        
    10         int count=0;
    11         vector<vector<int>> result(n,vector<int>(n));
    12         while(count<n*n)
    13         {
    14            
    15             for(int j=y1;j<=y2;j++)
    16             {
    17                 count++;
    18                 result[x1][j]=count;
    19             }              
    20             for(int i=x1+1;i<=x2;i++)
    21             {
    22                 count++;
    23                 result[i][y2]=count;
    24             }
    25            
    26             for(int j=y2-1;j>=y1;j--)
    27             {
    28                 count++;
    29                 result[x2][j]=count;
    30             }
    31            
    32             for(int i=x2-1;i>x1;i--)
    33             {
    34                 count++;
    35                 result[i][x1]=count;
    36             }
    37            
    38             x1++;y1++;x2--;y2--;
    39         }
    40        
    41         return result;
    42        
    43        
    44     }
    45 };
  • 相关阅读:
    Cyclic Nacklace HDU
    Oulipo HDU
    Period HDU
    Blue Jeans POJ
    剪花布条 HDU
    最长公共前缀 CSU
    Clock Pictures CSU
    Number Sequence HDU
    Arrange the Bulls POJ
    Traveling by Stagecoach POJ
  • 原文地址:https://www.cnblogs.com/reachteam/p/4211840.html
Copyright © 2020-2023  润新知