54. Spiral Matrix
Intitution
Complexity
Space Complexity
Time Complexity
Code
public List<Integer> spiralOrder(int[][] matrix) {
int totalElements = matrix.length * matrix[0].length;
List<Integer> result = new ArrayList<>();
int leftBound = 0, rightBound = matrix[0].length - 1;
int topBound = 0, bottomBound = matrix.length - 1;
while (totalElements > 0) {
// Traverse from left to right
for (int col = leftBound; col <= rightBound && totalElements > 0; col++) {
result.add(matrix[topBound][col]);
totalElements--;
}
topBound++;
// Traverse from top to bottom
for (int row = topBound; row <= bottomBound && totalElements > 0; row++) {
result.add(matrix[row][rightBound]);
totalElements--;
}
rightBound--;
// Traverse from right to left
for (int col = rightBound; col >= leftBound && totalElements > 0; col--) {
result.add(matrix[bottomBound][col]);
totalElements--;
}
bottomBound--;
// Traverse from bottom to top
for (int row = bottomBound; row >= topBound && totalElements > 0; row--) {
result.add(matrix[row][leftBound]);
totalElements--;
}
leftBound++;
}
return result;
}
Last updated