introw= matrix.length, col = matrix[0].length; ArrayList<Integer> res=newArrayList<>(row * col + 1); intleft=0, up = 0, down = row - 1, right = col - 1; while (left <= right && up <= down) { // left -> right for (inti= left; i <= right; i++) res.add(matrix[up][i]); // up -> down for (inti= up + 1; i <= down; ++i) res.add(matrix[i][right]); // right -> left if (up != down) { for (inti= right - 1; i >= left; --i) res.add(matrix[down][i]); } // down -> up if (left != right) { for (inti= down - 1; i > up; --i) res.add(matrix[i][left]); } left++; up++; down--; right--; } return res; } }