Java clean solution


  • 0
    public List<Integer> spiralOrder(int[][] matrix) {
        if (matrix == null) return null;
        List<Integer> res = new ArrayList<>();
        if (matrix.length == 0 || matrix[0].length == 0) {
            return res;
        }
        int m = matrix.length;
        int n = matrix[0].length;
        int lowerBound = -1, upperBound = m, leftBound = -1, rightBound = n;
        int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
        int direct = 0, x = 0, y = 0;
        while ( upperBound - lowerBound > 1 && rightBound - leftBound > 1) {
            direct = direct % 4;
            while ( y > lowerBound && y < upperBound && x > leftBound && x < rightBound) {
                res.add(matrix[y][x]);
                y += directions[direct][0];
                x += directions[direct][1];
            }
            if (direct == 0) {
                x--;
                y++;
                lowerBound++;
            }
            else if (direct == 1) {
                y--;
                x--;
                rightBound--;
            } 
            else if (direct == 2) {
                x++;
                y--;
                upperBound--;
            }
            else {
                x++;
                y++;
                leftBound++;
            }
            direct++;
        }
        return res;
    }

Log in to reply
 

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