Referred to the solution here.
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new LinkedList<>();
if (matrix.length == 0 || matrix[0].length == 0) {
return res;
}
int top = 0;
int left = 0;
int bottom = matrix.length - 1;
int right = matrix[0].length - 1;
while (left < right && top < bottom) {
for (int i = left; i < right; i++) {
res.add(matrix[top][i]);
}
for (int i = top; i < bottom; i++) {
res.add(matrix[i][right]);
}
for (int i = right; i > left; i--) {
res.add(matrix[bottom][i]);
}
for (int i = bottom; i > top; i--) {
res.add(matrix[i][left]);
}
top ++;
left ++;
bottom --;
right --;
}
if (left == right) {
for (int i = top; i <= bottom; i++) {
res.add(matrix[i][left]);
}
} else if (top == bottom) {
for (int i = left; i <= right; i++) {
res.add(matrix[top][i]);
}
}
return res;
}
}
class Solution {
public int[][] generateMatrix(int n) {
int[][] matrix = new int[n][n];
int left = 0;
int top = 0;
int right = n - 1;
int bottom = n - 1;
int j = 1;
while (left < right) {
for (int i = left; i < right; i++) {
matrix[top][i] = j++;
}
for (int i = top; i < bottom; i++) {
matrix[i][right] = j++;
}
for (int i = right; i > left; i--) {
matrix[bottom][i] = j++;
}
for (int i = bottom; i > top; i--) {
matrix[i][left] = j++;
}
left ++;
top ++;
right --;
bottom --;
}
if (left == right) {
matrix[top][left] = j;
}
return matrix;
}
}