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 ] ]
public int[][] generateMatrix(int n) {
if (n < 0)
return null;
int[][] matrix = new int[n][n];
int startRow = 0, startColumn = 0;
int endRow = n-1, endColumn = n-1;
int num = 1;
// Work on 2-D submatrix ranging from Row startRow to endRow,
// Column startColumn to endColumn
while (startRow < endRow && startColumn < endColumn) {
// Top edge, left-to-right
for (int k = startColumn; k < endColumn; k++)
matrix[startRow][k] = num++;
// Right edge, top-to-bottom
for (int k = startRow; k < endRow; k++)
matrix[k][endColumn] = num++;
// Bottom edge, right-to-left
for (int k = endColumn; k > startColumn; k--)
matrix[endRow][k] = num++;
// Left edge, bottom-to-top
for (int k = endRow; k > startRow; k--)
matrix[k][startColumn] = num++;
// Prepare to work on its nested submatrix
startRow++;
startColumn++;
endRow--;
endColumn--;
}
// When n is odd, there is still one cell at the center of the matrix
// that has not been assigned a value
if ((n & 1) == 1)
matrix[startRow][startColumn] = num;
return matrix;
}
Read full article from LeetCode - Spiral Matrix II | Darren's Blog
No comments:
Post a Comment