Skip to content

Instantly share code, notes, and snippets.

@Ray1988
Created September 22, 2013 00:07
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 ]
]
public class Solution {
public int[][] generateMatrix(int n) {
// Start typing your Java solution below
// DO NOT write main() function
if (n<=0){
return new int[0][0];
}
int [][] matrix=new int[n][n];
int beginX=0;
int endX=n-1;
int beginY=0;
int endY=n-1;
int current=1;
while (current<=n*n){
for (int col=beginX; col<=endX; col++){
matrix[beginY][col]=current++;
}
beginY++;
for (int row=beginY; row<=endY; row++){
matrix[row][endX]=current++;
}
endX--;
for (int col=endX; col>=beginX; col--){
matrix[endY][col]=current++;
}
endY--;
for (int row=endY; row>=beginY; row--){
matrix[row][beginX]=current++;
}
beginX++;
}
return matrix;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment