package com.zerroi.leetcode.Three16; import java.util.ArrayList; import java.util.List; public class SpiralOrder { } class SolutionSecond { public List spiralOrder(int[][] matrix) { List res = new ArrayList<>(); int left = 0, right = matrix.length; int top = 0, bottom = matrix[0].length; int len = right * bottom; int i = 0; while (i < len) { for (int j = left; j < right; j++) { res.add(matrix[top][j]); ++i; if (i >= len) return res; } ++top; for (int j = top; j < bottom; j++) { res.add(matrix[j][right - 1]); ++i; if (i >= len) return res; } --right; for (int j = right - 1; j >= left; j--) { res.add(matrix[bottom-1][j]); ++i; if (i >= len) return res; } ++left; for (int j = bottom - 1; j >= top; j--) { res.add(matrix[j][left]); ++i; if (i >= len) return res; } --bottom; } return res; } }