1class Solution {2public List<Integer> spiralOrder(int[][] matrix) {3List<Integer> ans = new ArrayList<>();4int top = 0, left = 0, bottom = matrix.length - 1, right = matrix[0].length - 1;56while (top <= bottom && left <= right) {7for (int i = left; i <= right; i++) ans.add(matrix[top][i]);8top++;910for (int i = top; i <= bottom; i++) ans.add(matrix[i][right]);11right--;1213if (top <= bottom) {14for (int i = right; i >= left; i--) ans.add(matrix[bottom][i]);15bottom--;16}1718if (left <= right) {19for (int i = bottom; i >= top; i--) ans.add(matrix[i][left]);20left++;21}22}23return ans;24}25}