Monday, May 11, 2015

Spiral Matrix II

来源:Leetcode

原帖:http://oj.leetcode.com/problems/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) {  
     if (n == 0) return {};  
     vector<vector<int> > res(n, vector<int>(n));  
     int imin = 0, imax = n - 1;  
     int jmin = 0, jmax = n - 1;  
     int number = 1;    
     while (1) {  
       for (int j = jmin; j <= jmax; ++j) res[imin][j] = number++;          
       if (++imin > imax) break;  
       
       for (int i = imin; i <= imax; ++i) res[i][jmax] = number++;          
       if (jmin > --jmax) break;  
   
       for (int j = jmax; j >= jmin; --j) res[imax][j] = number++;          
       if (imin > --imax) break;  
   
       for (int i = imax; i >= imin; --i) res[i][jmin] = number++;          
       if (++jmin > jmax) break;  
     }    
     return res;  
   }  
 };  

No comments:

Post a Comment