A simple and readable solution


  • 1
    0
    Input :  
      1 2 3
      4 5 6 
      7 8 9 
    
    1st iteration of while loop : startRow = 0; endRow = 2; startCol = 0; endCol = 2;
      1st for loop : 1 2 3
      2nd for loop : 6 9
      3rd for loop : 8 7
      4th for loop : 4
    
    2nd iteration of while loop : startRow = 1; endRow = 1; startCol = 1; endCol = 1;
      1st for loop : 5
      2nd for loop : -
      3rd for loop : -
      4th for loop : -
      
    While loop breaks and result list is returned.
    
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            
            if(matrix == null || matrix.length <= 0)
                return new ArrayList<Integer>();
                
            // Result list
            List<Integer> result = new ArrayList<Integer>();
            
            // array boundaries
            int startRow = 0;
            int endRow = matrix.length-1;
            
            int startCol = 0;
            int endCol = matrix[0].length-1;
            
            while( startRow <= endRow && startCol <= endCol)
            {
                
                //Print first row
                for(int j=startCol; j <= endCol; j++)
                  result.add( matrix[startRow][j] );
                
                //Print last column
                for(int i= (startRow+1); i <= endRow; i++)
                  result.add(matrix[i][endCol]);
                
                //Print last row
                if( startRow != endRow ) // This condition is to handle the case where input contains only 1 row and n columns
                {
                    for(int k = (endCol-1); k >= startCol; k-- )
                      result.add( matrix[endRow][k] );
                }
                
                //Print first column
                if(startCol != endCol) // This condition is to handle the case where input contains only m rows and 1 column
                {
                    for(int l=(endRow-1); l > startRow; l--)
                      result.add( matrix[l][startCol] );
                }
                
                startRow += 1;
                startCol += 1;
                
                endRow -= 1;
                endCol -= 1;
            }
            
            return result;
        }
    }

Log in to reply
 

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