首页 > 代码库 > 【leetcode】Spiral Matrix II

【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 };

 

【leetcode】Spiral Matrix II