LeetCode 54.

Tags:

Complexity

  • Time complexity: O(n)

  • Space complexity: O(n)

Code

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {

        List<Integer> result = new ArrayList<Integer>();
        int width = matrix[0].length;
        int height = matrix.length;
        
        int countX = width, countY = height-1;

        int w = -1, h = 0;
        int flag = 1; // 1:right 2:down 3:left 4:up

        while (result.size() < height * width) {
            int count = 0;
            if (flag == 1) { //right
                w++; // move right: initial start point
                while (count < countX) {
                    result.add(matrix[h][w + count]);
                    count++;
                }
                countX--;
                w = w + countX;
            }else if (flag == 2) { //down
                h++;
                while (count < countY) {
                    result.add(matrix[h + count][w]);
                    count++;
                }
                countY--;
                h = h + countY;
            }else if (flag == 3) { //left
                w--;
                while (count < countX) {
                    result.add(matrix[h][w - count]);
                    count++;
                }
                countX--;
                w = w - countX;
            }else if (flag == 4) { //up
                h--;
                while (count < countY) {
                    result.add(matrix[h - count][w]);
                    count++;
                }
                countY--;
                h = h - countY;
            }

            if (++flag > 4) flag = 1;
        }

        return result;
    }
}

Check out the description of this problem at LC 54.