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 =
You should return the following matrix:Given n =
3
,[ [ 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> > matrix(n, vector<int>(n,0));//result int dec = 0;//decrement count int row = 0;//start row int col = 0;//start col int lastIndex = 0; int const n2 = n*n; int counter = 1; while(1){ lastIndex = n-1 -dec + col; for(int ii = col; ii <= lastIndex; ++ii){//left to right matrix[row][ii] = counter++; } col = lastIndex; ++row; ++dec; if (counter > n2) return matrix; lastIndex = n-1 -dec + row; for(int ii = row; ii <= lastIndex; ++ii){//up to down matrix[ii][col] = counter++; } row = lastIndex; --col; if (counter > n2) return matrix; lastIndex = col - (n-1-dec); for(int ii = col; ii >= lastIndex; --ii){//right to left matrix[row][ii] = counter++; } col = lastIndex; --row; ++dec; if (counter > n2) return matrix; lastIndex = dec + row + 1 - n; for(int ii = row; ii >= lastIndex; --ii){//down to up matrix[ii][col] = counter++; } row = lastIndex; ++col; if (counter > n2) return matrix; } return matrix; } };
No comments:
Post a Comment