Created
August 15, 2014 05:27
-
-
Save xiren-wang/752151c6f0ff09b64132 to your computer and use it in GitHub Desktop.
Spiral Matrix II. Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
vector<vector<int> > generateMatrix(int n) { | |
vector<vector<int> > vvInt(n, vector<int>(n,0)); | |
//fill two strips consecutively, | |
// First row, last col, last row, first col | |
//Note that if n is odd (n >=3), the central one is NOT filled (it's not in four-strip structure) | |
int rowStart = 0, colStart = 0; | |
int scan = 1; | |
while (rowStart < n) { | |
// first row [row, col].... [row, n-1-colStart-1] | |
int row=rowStart, col=colStart; | |
for(; col<=n-1-colStart-1; col++) { | |
vvInt[row][col] = scan ++; | |
} | |
col = n-1-colStart; //set for sure | |
//last col, [row, n-1-colStart] ... [n-1-rowStart-1, n-1-colStart] | |
for(; row<=n-1-rowStart-1; row++) { | |
vvInt[row][col] = scan ++; | |
} | |
row = n-1-rowStart; | |
//last row, [n-1-rowStart, n-1-colStart] -- [n-1-rowStart, colStart+1] | |
for(; col >= colStart+1; col--) { | |
vvInt[row][col] = scan ++; | |
} | |
col = colStart; | |
// first col, [n-1-rowStart, colStart] ... [rowStart, colStart] | |
for(; row>=rowStart+1; row --) { | |
vvInt[row][col] = scan ++; | |
} | |
//this circle done; go inside | |
rowStart ++; | |
colStart ++; | |
} | |
// above it's assumed matrix has four-strips, so when n is odd, the centeral one is NOT filled | |
if (n %2 ) | |
vvInt[n/2][n/2] = scan; | |
return vvInt; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment