AlgoMaster Logo

Spiral Matrix

matrix=[[1,2,3],[4,5,6],[7,8,9]]
1public List<Integer> spiralOrder(int[][] matrix) {
2    List<Integer> result = new ArrayList<>();
3    int top = 0, bottom = matrix.length - 1;
4    int left = 0, right = matrix[0].length - 1;
5
6    while (top <= bottom && left <= right) {
7        // Traverse right
8        for (int col = left; col <= right; col++) {
9            result.add(matrix[top][col]);
10        }
11        top++;
12
13        // Traverse down
14        for (int row = top; row <= bottom; row++) {
15            result.add(matrix[row][right]);
16        }
17        right--;
18
19        // Traverse left
20        if (top <= bottom) {
21            for (int col = right; col >= left; col--) {
22                result.add(matrix[bottom][col]);
23            }
24            bottom--;
25        }
26
27        // Traverse up
28        if (left <= right) {
29            for (int row = bottom; row >= top; row--) {
30                result.add(matrix[row][left]);
31            }
32            left++;
33        }
34    }
35
36    return result;
37}
0 / 19
123456789