LC-54 Spiral Matrix

Question: Given a matrix and display its elements in spiral order

Solution: every time loop a circle. First we need to make sure the vertex position of circle corner. Then start looping.

class Solution {
public List spiralOrder(int[][] matrix) {
List res = new ArrayList<>();
if(matrix == null || matrix.length==0) return res;
int r1 = 0, r2 = matrix.length - 1;
int c1 = 0, c2 = matrix[0].length - 1;
while(r1<=r2 && c1<=c2){
for(int i=c1; i<=c2; i++){
res.add(matrix[r1][i]);
}
for(int j=r1+1; j<=r2; j++){
res.add(matrix[j][c2]);
}
if(r1 < r2 && c1 < c2){
for(int i=c2-1; i>=c1; i--) res.add(matrix[r2][i]);
for(int j=r2-1; j>r1; j--) res.add(matrix[j][c1]);
}
r1 ++;
r2 --;
c1 ++;
c2 --;
}
return res;
}
}