A Java solution


  • 0
    J
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> list = new ArrayList<Integer>();
            if (matrix == null || matrix.length == 0){
                return list;
            }
            int m = matrix.length, n = matrix[0].length;
            int x = 0;
            int y = n - 1;
            int dir = 1;
            int mx = m - 1, ny = n - 1;
            for (int i = 0; i < n; i++){
                list.add(matrix[0][i]);
            }
            if (mx == 0){
                return list;
            }
            while (mx > 0 && ny > 0){
                if (dir == 0){
                    for (int i = 0; i < ny; i++){
                        list.add(matrix[x][++y]);
                    }
                    
                    ny--;
                    dir++;
                } else if (dir == 1){
                    for (int i = 0; i < mx; i++){
                        list.add(matrix[++x][y]);
                    }
                    mx--;
                    dir++;
                } else if (dir == 2){
                    for (int i = 0; i < ny; i++){
                        list.add(matrix[x][--y]);
                    }
                    ny--;
                    dir++;
                } else {
                    for (int i = 0; i < mx; i++){
                        list.add(matrix[--x][y]);
                    }
                    mx--;
                    dir = 0;
                }
            }
            
            if (mx == 0 && ny != 0){
                if (dir == 0){
                    for (int i = 0; i < ny; i++){
                        list.add(matrix[x][++y]);
                    }
                } else {
                    for (int i = 0; i < ny; i++){
                        list.add(matrix[x][--y]);
                    }
                }
            } else if (ny == 0 && mx != 0){
                if (dir == 1){
                    for (int i = 0; i < mx; i++){
                        list.add(matrix[++x][y]);
                    }
                } else {
                    for (int i = 0; i < mx; i++){
                        list.add(matrix[--x][y]);
                    }
                }
            }
            
            return list;
        }
    }
    

Log in to reply
 

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