← Arrays

Spiral Matrix

Medium
Python
def spiral_order(matrix):
    res=[]
    while matrix:
        res+=matrix.pop(0)
        matrix=list(zip(*matrix))[::-1]
    return res
Java
public List<Integer> spiralOrder(int[][] m){
    List<Integer> res=new ArrayList<>();
    while(m.length>0&&m[0].length>0){
        for(int x:m[0]) res.add(x);
        int[][] t=new int[m[0].length][m.length-1];
        for(int r=1;r<m.length;r++) for(int c=m[r].length-1;c>=0;c--) t[c][r-1]=m[r][c];
        m=t;
    } return res;
}

Key Insight

zip(*matrix) is Python's most powerful matrix trick.

Python → Java Differences

  • zip(*matrix) Python transpose trick
  • [::-1] rotation vs loops
  • Java needs explicit transposition
Python
def spiral_order(matrix):
    res=[]
    while matrix:
        res+=matrix.pop(0)
        matrix=list(zip(*matrix))[::-1]
    return res
Java
public List<Integer> spiralOrder(int[][] m){
    List<Integer> res=new ArrayList<>();
    while(m.length>0&&m[0].length>0){
        for(int x:m[0]) res.add(x);
        int[][] t=new int[m[0].length][m.length-1];
        for(int r=1;r<m.length;r++) for(int c=m[r].length-1;c>=0;c--) t[c][r-1]=m[r][c];
        m=t;
    } return res;
}

Algorithm Steps

1. Take top row
2. Rotate 90 degrees
3. Repeat