Blind 75
Spiral Matrix
- Problem
- LC 54
- Category
- Matrix
- File
- blind75_LC54SpiralMatrix.java
- Path
- pkg5leetcode/blind75/blind75_LC54SpiralMatrix.java
- Package
- pkg5leetcode.blind75
- Command
- java pkg5leetcode/blind75/blind75_LC54SpiralMatrix.java
- Approach
- Layer-by-layer traverse top/bottom/left/right bounds.
- Complexity
- Time O(mn), Space O(1) excluding output
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg5leetcode.blind75;2 3/*4 * Spiral Matrix | LC 545 * APPROACH: Layer-by-layer traverse top/bottom/left/right bounds.6 * COMPLEXITY: Time O(mn), Space O(1) excluding output7 */8import java.util.*;9 10public class blind75_LC54SpiralMatrix {11 static List<Integer> spiralOrder(int[][] matrix) {12 List<Integer> res = new ArrayList<>();13 int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1;14 while (top <= bottom && left <= right) {15 for (int j = left; j <= right; j++) res.add(matrix[top][j]);16 top++;17 for (int i = top; i <= bottom; i++) res.add(matrix[i][right]);18 right--;19 if (top <= bottom) {20 for (int j = right; j >= left; j--) res.add(matrix[bottom][j]);21 bottom--;22 }23 if (left <= right) {24 for (int i = bottom; i >= top; i--) res.add(matrix[i][left]);25 left++;26 }27 }28 return res;29 }30 31 public static void main(String[] args) {32 check(spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}).equals(Arrays.asList(1, 2, 3, 6, 9, 8, 7, 4, 5)), "case1");33 check(spiralOrder(new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}).equals(Arrays.asList(1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7)), "case2");34 System.out.println("all tests passed");35 }36 37 static void check(boolean cond, String name) {38 if (!cond) throw new AssertionError("FAILED: " + name);39 System.out.println(" PASS " + name);40 }41}