Java-Simple and Clean Solution


  • 5
    V

    // 1 2 3 4 5

    // 14 15 16 17 6

    // 13 18 19 20 7

    // 12 11 10 9 8

    // direction =0 left to right
    // direction =1 top to bottom
    // direction =2 right to left
    // direction =3 bottom to top

    public class Solution {

    public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> result = new ArrayList<Integer>();
            if(matrix.length == 0) return result;
            int left=0,right=matrix[0].length-1,top=0,bottom=matrix.length-1,direction=0;
            while(left <= right && top <= bottom){
                if(direction == 0){
                    for(int i=left;i<= right;i++){
                        result.add(matrix[top][i]);
                    }
                    top++;
                }
                else if(direction == 1){
                    for(int i=top;i<=bottom;i++){
                        result.add(matrix[i][right]);
                    }
                    right--;
                }
                else if(direction == 2){
                    for(int i=right;i>=left;i--){
                        result.add(matrix[bottom][i]);
                    }
                    bottom--;
                    
                }
                else if(direction == 3){
                    for(int i=bottom;i>=top;i--){
                        result.add(matrix[i][left]);
                    }
                    left++;
                }
                direction=(direction+1) % 4;
            }
        return result;
    }
    

    }


Log in to reply
 

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