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) {
int startx = 0,starty = 0,endx = n-1,endy = n-1;
int[][] ans = new int[n][n];
int count = 1;
while(startx <= endx && starty <= endy){
for(int i = startx;i<=endx;i++){
ans[starty][i] = count++;
}
starty++;
for(int i = starty;i<=endy;i++){
ans[i][endx] = count++;
}
endx--;
for(int i = endx;i>=startx;i--){
ans[endy][i] = count++;
}
endy--;
for(int i = endy;i>=starty;i--){
ans[i][startx] = count++;
}
startx++;
}
return ans;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int left = 0, right = n-1, top = 0, bottom = n-1;
int counter = 0;
int[][] res = new int[n][n];
while(top <= bottom && left <= right){
for(int i=left; i<=right; i++){
res[top][i] = ++counter;
}
top++;
for(int i=top; i<=bottom; i++){
res[i][right] = ++counter;
}
right--;
for(int i=right; i>=left; i--){
res[bottom][i] = ++counter;
}
bottom--;
for(int i=bottom; i>=top; i--){
res[i][left] = ++counter;
}
left++;
}
return res;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int totItr = 2 * n - 1;
int[][] mat = new int[n][n];
int startRow = 0;
int endRow = n - 1;
int startCol = 0;
int endCol = n - 1;
int count = 1;
for (int i = 0; i < totItr; i++) {
for (int j = startCol; j <= endCol; j++) {
mat[startRow][j] = count++;
}
startRow++;
for (int j = startRow; j <= endRow; j++) {
mat[j][endCol] = count++;
}
endCol--;
for(int j = endCol; j>= startCol; j--) {
mat[endRow][j] = count++;
}
endRow--;
for(int j = endRow; j>= startRow; j--) {
mat[j][startCol] = count++;
}
startCol++;
}
return mat;
}
}