Leetcode 3248. Snake in Matrix
You have been given a matrix of size m x n. Your task is to return a list of integers representing the matrix in a “snake-like” order. The snake-like pattern starts from the top-left corner and moves to the end of the row, then changes direction, moves down to the next row, and repeats the process.
m
and n
?m
and n
are such that ( 0 \leq m, n \leq 1000 ).For a matrix:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
The snake-like order would be:
[1, 2, 3, 6, 5, 4, 7, 8, 9]
To solve this problem, we can:
The steps are as follows:
import java.util.ArrayList;
import java.util.List;
public class SnakeInMatrix {
public List<Integer> snakeOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
if (matrix == null || matrix.length == 0) {
return result;
}
int m = matrix.length;
int n = matrix[0].length;
for (int i = 0; i < m; i++) {
if (i % 2 == 0) {
// Move left to right for even-indexed rows
for (int j = 0; j < n; j++) {
result.add(matrix[i][j]);
}
} else {
// Move right to left for odd-indexed rows
for (int j = n - 1; j >= 0; j--) {
result.add(matrix[i][j]);
}
}
}
return result;
}
// Helper method to print the result
public static void main(String[] args) {
SnakeInMatrix sim = new SnakeInMatrix();
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(sim.snakeOrder(matrix)); // Output: [1, 2, 3, 6, 5, 4, 7, 8, 9]
}
}
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 we iterate over each element in the matrix exactly once.
The space complexity is O(m * n) for the result list which stores all the elements of the matrix.
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?