My JAVA solution


  • 1
    Q
    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> spiral = new ArrayList<Integer>();
    		if (matrix.length ==0){
    			return spiral;
    		}
    	    int startI = 0; 
    	    int startJ = 0;        
    	    int endI = matrix.length-1;
    	    int endJ = matrix[0].length-1;
    	    
    	    do{ 
    	    	for (int j=startJ;j<=endJ;j++){
    	        	spiral.add(matrix[startI][j]);
    	        }
    	    	for (int i=startI+1;i<=endI;i++){
    	        	spiral.add(matrix[i][endJ]);
    	        }
    	        if (endI > startI){
    		        for (int j=endJ-1;j>=startJ;j--){
    		        	spiral.add(matrix[endI][j]);
    		        }
    	        }
    	        if (endJ>startJ){
    		        for (int i=endI-1;i>=startI+1;i--){
    		        	spiral.add(matrix[i][startJ]);
    		        }
    	        }
    	        startI++;
    	        endI--;
    	        startJ++;
    	        endJ--;
    	    }while(endI>=startI && endJ>=startJ);
    	    
    	    return spiral;
        }
    }

  • 0
    M

    Neat solution!


Log in to reply
 

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