java

spiralOrder

/**
     * Input:
     [
     [ 1, 2, 3 ],
     [ 4, 5, 6 ],
     [ 7, 8, 9 ]
     ]

     Output: [1,2,3,6,9,8,7,4,5]


     * @param matrix
     * @return
     */
    public List<Integer> spiralOrder(int[][] matrix) {
        String spiralDirection="RIGHT";
        int startRow=0;
        int startColumn=0;
        int k=0;
        if (matrix==null || matrix.length==0)
            return new ArrayList<>();
        int row = matrix.length;
        int lastRow= row-1;
        int column = matrix[0].length;
        int lastColumn = column-1;
        List<Integer> spiralOrder= new ArrayList<>();

        while (k<row*column) {
            switch (spiralDirection){
                case "RIGHT":
                    for (int i = startRow, j = startColumn; j <= lastColumn; j++) {
                        spiralOrder.add(matrix[i][j]);
                        k++;
                    }
                    startRow++;
                    spiralDirection = "DOWN";
                    break;

                case "DOWN":
                    for (int i = startRow, j = lastColumn; i <= lastRow; i++) {
                        spiralOrder.add(matrix[i][j]);
                        k++;
                    }
                    lastColumn--;
                    spiralDirection = "LEFT";
                    break;

                case "LEFT":
                    for (int i = lastRow, j = lastColumn; j >= startColumn; j--) {
                        spiralOrder.add(matrix[i][j]);
                        k++;
                    }
                    lastRow--;
                    spiralDirection = "UP";
                    break;

                case "UP":
                    for (int i = lastRow, j = startColumn; i >= startRow; i--) {
                        spiralOrder.add(matrix[i][j]);
                        k++;
                    }
                    startColumn++;
                    spiralDirection = "RIGHT";
                    break;

                    default:
                        break;
            }
        }
        return spiralOrder;
    }
Was this helpful?