Given an m x n
matrix, return all elements of the matrix in spiral order.
Input: matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
matrix = []
)?
To solve this problem, we will employ the following strategy:
top
, bottom
, left
, and right
.Here is the Java code implementing this strategy:
import java.util.ArrayList;
import java.util.List;
public class SpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0) {
return result;
}
int top = 0;
int bottom = matrix.length - 1;
int left = 0;
int right = matrix[0].length - 1;
while (top <= bottom && left <= right) {
// Traverse from left to right along the top row
for (int i = left; i <= right; i++) {
result.add(matrix[top][i]);
}
top++;
// Traverse from top to bottom down the right column
for (int i = top; i <= bottom; i++) {
result.add(matrix[i][right]);
}
right--;
// Traverse from right to left along the bottom row, if not already traversed
if (top <= bottom) {
for (int i = right; i >= left; i--) {
result.add(matrix[bottom][i]);
}
bottom--;
}
// Traverse from bottom to top up the left column, if not already traversed
if (left <= right) {
for (int i = bottom; i >= top; i--) {
result.add(matrix[i][left]);
}
left++;
}
}
return result;
}
public static void main(String[] args) {
SpiralMatrix sm = new SpiralMatrix();
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(sm.spiralOrder(matrix)); // Output: [1, 2, 3, 6, 9, 8, 7, 4, 5]
}
}
The time complexity of this solution is O(m * n)
, where m
is the number of rows and n
is the number of columns in the matrix. This is because each element of the matrix is visited exactly once.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?