public int[][] generateMatrix(int n) {
// Note: The Solution object is instantiated only once and is reused by each test case.
int start = 0;
int end = n-1;
int[][] res = new int[n][n];
int num = 1;
//This is the special case of n=1
if (start == end) {
res[start][start] = num;
return res;
}
//Regular case
while (start < end) {
//from Left to Right
for (int i=start; i<end; i++) {
res[start][i] = num;
num++;
}
//from Up to Bottom
for (int i=start; i<end; i++) {
res[i][end] = num;
num++;
}
//from Right to Left
for (int i=end; i>start; i--) {
res[end][i] = num;
num++;
}
//from Bottom to Up
for (int i=end; i>start; i--) {
res[i][start]=num;
num++;
}
start++;
end--;
if (start==end) res[start][start] = num;
}
return res;
}
No comments:
Post a Comment