Java naive solution


  • 0
    A
    public class Solution {
        
        public static final int RIGHT = 0;
        public static final int BOTTOM = 1;
        public static final int LEFT = 2;
        public static final int TOP = 3;
    
        public List<Integer> spiralOrder(int[][] matrix) {
            
            if (matrix.length == 0 || matrix[0].length == 0) {
                return new LinkedList<>();
            }
            
            List<Integer> res = new ArrayList<>(matrix.length * matrix[0].length);
            
            int row = 0;
            int col = 0;
            
            int top = 0;
            int left = 0;
            int right = matrix[0].length - 1;
            int bottom = matrix.length - 1;
            
            int dir = RIGHT;
            
            while (left <= right && top <= bottom) {
                
                switch(dir) {
                    case RIGHT: {
                        while(col < right) {
                            res.add(matrix[row][col]);
                            col++;
                        }
                        dir = BOTTOM;
                        top++;
                        break;
                    }
                    case BOTTOM: {
                        while(row < bottom) {
                            res.add(matrix[row][col]);
                            row++;
                        }
                        dir = LEFT;
                        right--;
                        break;
                    }
                    case LEFT: {
                        while(col > left) {
                            res.add(matrix[row][col]);
                            col--;
                        }
                        dir = TOP;
                        bottom--;
                        break;
                    }
                    case TOP: {
                        while(row > top) {
                            res.add(matrix[row][col]);
                            row--;
                        }
                        dir = RIGHT;
                        left++;
                        break;
                    }
                }
                
            }
            
            res.add(matrix[row][col]);
            
            return res;
        }
    
    }

Log in to reply
 

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