Spiral matrix
Prashant Mishra

Prashant Mishra @prashantrmishra

About: There is always a price for those who persevere.

Location:
India
Joined:
Jul 2, 2022

Spiral matrix

Publish Date: Feb 15
0 0

Problem

TC: O(n*m)

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        int left =0,right = matrix[0].length-1;
        int top  =0, bottom  = matrix.length-1;
        int dir =0;
        List<Integer> list = new ArrayList<>();
        while(left<=right && top<=bottom){
            if(dir ==0){
                for(int i = left;i<=right;i++){
                    list.add(matrix[top][i]);
                }
                top++;
            }
            else if(dir ==1){
                for(int i=top;i<=bottom;i++){
                    list.add(matrix[i][right]);
                }
                right--;
            }
            else if(dir ==2){
                for(int i = right;i>=left;i--){
                    list.add(matrix[bottom][i]);
                }
                bottom--;
            }
            else{
                for(int i = bottom;i>=top;i--){
                    list.add(matrix[i][left]);
                }
                left++;
            }

            dir = (dir+1)%4;
        }
        return list;
    }
}
Enter fullscreen mode Exit fullscreen mode

Comments 0 total

    Add comment