Most concise Java Solution


  • 1
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res = new LinkedList<>();
            if(matrix==null || matrix.length==0)
                return res;
                
            int left=0, right=matrix[0].length-1;
            int up=0, down=matrix.length-1;
            
            while(left<=right&&up<=down){ // check if boundaries are valid
               for(int i=left;i<=right;++i){
                   res.add(matrix[up][i]);
               }
               up++;
               for(int i=up;i<=down;++i){
                   res.add(matrix[i][right]);
               }
               right--;
               
               if(left>right || up>down)  // check if boundaries are still valid
                    break;
               for(int i=right;i>=left;--i){
                   res.add(matrix[down][i]);
               }
               down--;
               for(int i=down;i>=up;--i){
                   res.add(matrix[i][left]);
               }
               left++;
            }
            
            return res;        
        }
    }

  • 0
    P

    @UpTheHell why is following check needed

    if(left>right || up>down) // check if boundaries are still valid
    break;


Log in to reply
 

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