One Loop Java Solution


  • 0
    J
    public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> intList = new ArrayList<Integer>();
            if (matrix.length == 0 || matrix[0].length == 0)
                return intList;
            int row = 0, col = 0, counted = 0, shiftIndice = 0, rowMin = 0, colMin = 0;
            int rowMax = matrix.length, colMax = matrix[0].length;
            int[][] shift = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
            while (counted < matrix.length * matrix[0].length) {
                counted++;
                intList.add(matrix[row][col]);
                int nextRow = row + shift[shiftIndice][0];
                int nextCol = col + shift[shiftIndice][1];
                //can we continue in this direction
                if (!(nextRow < rowMax && nextRow >= rowMin && nextCol < colMax && nextCol >= colMin)) {
                    //change directions
                    shiftIndice = (shiftIndice + 1) % 4;
                    nextRow = row + shift[shiftIndice][0];
                    nextCol = col + shift[shiftIndice][1];
                    //update mins and maxes
                    rowMin = Math.max(rowMin + shift[shiftIndice][0], rowMin);
                    rowMax = Math.min(rowMax + shift[shiftIndice][0], rowMax);
                    colMin = Math.max(colMin + shift[shiftIndice][1], colMin);
                    colMax = Math.min(colMax + shift[shiftIndice][1], colMax);
                }
                row = nextRow;
                col = nextCol;
            }
            return intList;
        }
    

Log in to reply
 

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