L59. Spiral Matrix II
Problem:
Given a positive integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
Solution:
temp = 1 since we start at 1 instead of 0;
public int[][] generateMatrix(int n) {
if(n <= 0) return null;
final int[][] result = new int[n][n];
int rowStart = 0, colStart = 0;
int rowEnd = n-1, colEnd = n-1;
int temp = 1;
while(rowStart <= rowEnd && colStart <= colEnd){
//Traverse right
for(int i = colStart; i <= colEnd; i++){
result[rowStart][i] = temp++;
}
rowStart++;
//Traverse down
for(int i = rowStart; i <= rowEnd; i++){
result[i][colEnd] = temp++;
}
colEnd--;
//Taverse left
if(rowEnd >= rowStart){
for(int i = colEnd; i >= colStart; i--){
result[rowEnd][i] = temp++;
}
rowEnd--;
}
//up
if(colEnd >= colStart){
for(int i = rowEnd; i >= rowStart; i--){
result[i][colStart] = temp++;
}
colStart++;
}
}
return result;
}
Last updated
Was this helpful?