My accepted Java solution


  • 0
    D

    We can read the matrix layer by layer. And the number of layer is Math.min(rows + 1, cols + 1) / 2.
    For each layer, we can read the number of the first row, then the last column, then the last row, then the first column.

    public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix.length <= 0) {
            return new ArrayList<Integer>(0);
        }
        int rows = matrix.length;
        int cols = matrix[0].length;
        List<Integer> ans = new ArrayList<Integer>(rows * cols);
        for (int i = 0; i < Math.min(rows + 1, cols + 1) / 2; i++) {
            // first row
            for (int j = i; j < cols - i; j++) {
                ans.add(matrix[i][j]);
            }
            // last column
            for (int j = i + 1; j < rows - i; j++) {
                ans.add(matrix[j][cols - i - 1]);
            }
            // last row if exists
            for (int j = cols - i - 2; j >= i && rows - i - 1 > i; j--) {
                ans.add(matrix[rows - i - 1][j]);
            }
            // first column if exists
            for (int j = rows - i - 2; j > i && i < cols - i - 1; j--) {
                ans.add(matrix[j][i]);
            }
        }
        return ans;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.