Java AC solution


  • 0
    N
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<Integer>();
        if (matrix.length == 0) return list;
        int[] dir = {0, matrix.length - 1, 0, matrix[0].length - 1};
        int direction = 0;
        while (dir[0] <= dir[1] && dir[2] <= dir[3]) {
            if (direction % 4 == 0) {
                for (int i = dir[2]; i <= dir[3]; i++) list.add(matrix[dir[0]][i]);
                dir[0]++;
            } else if (direction % 4 == 1) {
                for (int i = dir[0]; i <= dir[1]; i++) list.add(matrix[i][dir[3]]);
                dir[3]--;
            } else if (direction % 4 == 2) {
                for (int i = dir[3]; i >= dir[2]; i--) list.add(matrix[dir[1]][i]);
                dir[1]--;
            } else {
                for (int i = dir[1]; i >= dir[0]; i--) list.add(matrix[i][dir[2]]);
                dir[2]++;
            }
            direction++;
        }
        return list;
    }

Log in to reply
 

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