class Solution { public int[] spiralOrder(int[][] matrix) { int m = matrix.length; if(m == 0) return new int[]{}; int n = matrix[0].length; if(m == 1) return matrix[0]; if(n == 0) return new int[]{}; int[] res = new int[m*n]; int k = 0; int row_start=0,row_end = m,col_start = 0,col_end = n; while (row_start<row_end && col_start<col_end) { for (int i = col_start; i < col_end; i++) { res[k++] = matrix[row_start][i]; } if(k == m*n) return res; row_start++; for (int j = row_start; j < row_end; j++) { res[k++] = matrix[j][col_end-1]; } if(k == m*n) return res; col_end--; for (int i = col_end - 1; i >= col_start; i--) { res[k++] = matrix[row_end-1][i]; } if(k == m*n) return res; row_end--; for (int j = row_end - 1; j >= row_start; j--) { res[k++] = matrix[j][col_start]; } if(k == m*n) return res; col_start++; } return res; } }