Super Clean AC JAVA solution


  • 0
    W

    The idea is to use an offset to control the traversal.

        public List<Integer> spiralOrder(int[][] matrix) {
            int row = matrix.length;
            List<Integer> res = new ArrayList<>();
            if (row == 0) return res;
            int col = matrix[0].length;
            if (col == 0) return res;
            
            int offset = 0;
            while (res.size() < row * col) {
                for (int i = 0 + offset; i < col - offset; i++) {
                    res.add(matrix[offset][i]);
                }
                if (res.size() >= row * col) break;
                for (int i = 1 + offset; i < row - offset - 1; i++) {
                    res.add(matrix[i][col - 1 - offset]);
                }
                if (res.size() >= row * col) break;
                for (int i = col - 1 - offset; i >= offset; i--) {
                    res.add(matrix[row - 1 - offset][i]);
                }
                if (res.size() >= row * col) break;
                for (int i = row - offset - 2; i > offset; i--) {
                    res.add(matrix[i][offset]);
                }
                offset++;
            }
            
            return res;
        }
    

Log in to reply
 

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