def spiral_order(matrix):
res=[]
while matrix:
res+=matrix.pop(0)
matrix=list(zip(*matrix))[::-1]
return res
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;
}
zip(*matrix) is Python's most powerful matrix trick.
def spiral_order(matrix):
res=[]
while matrix:
res+=matrix.pop(0)
matrix=list(zip(*matrix))[::-1]
return res
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;
}
1. Take top row 2. Rotate 90 degrees 3. Repeat