fishercoder1534/Leetcode

54. Spiral Matrix - LeetCode

Tejas07PSK opened this issue ยท 2 comments

Time complexity of this program is fine O(n*m), but space complexity can be O(1).
Here is my code,

import java.util.ArrayList;
import java.util.List;

class Solution 
{
    public List<Integer> spiralOrder(int[][] A) 
    {
        
        if ((A == null) || (A.length == 0) || (A[0].length == 0))
        {
            
            return (new ArrayList <Integer> ());
            
        }
        int lr = 0, ur = A.length, lc = 0, uc = A[0].length;
        List <Integer> arr = new ArrayList <Integer> ();
        int count = 0, t = 0, x = 0, y = 0;
        int offset [] = {0, 1};
        while (count < (A.length * A[0].length))
        {

            if (((y + offset[1]) == uc) || ((x + offset[0]) == ur) || ((y + offset[1]) < lc) || ((x + offset[0]) < lr))
            {

                if (((y + offset[1]) == uc))
                {

                    lr += 1;

                }
                else if (((x + offset[0]) == ur))
                {

                    uc -= 1;

                }
                else if (((y + offset[1]) < lc))
                {

                    ur -= 1;

                }
                else if (((x + offset[0]) < lr))
                {

                    lc += 1;

                }
                t = offset[0];
                offset[0] = offset[1];
                offset[1] = -t;

            }
            arr.add(A[x][y]);
            x += offset[0];
            y += offset[1];
            count += 1;

        }
        return (arr);
        
    }
}


Let me know what you think sir, ๐Ÿ˜‰ ๐Ÿ˜„ .
If you don't consider the array to be returned and just print the values as they are, space complexity will be O(1).

public class solution {

public static void spiralPrint(int matrix[][]){
	int m = matrix.length;
    int n = matrix[0].length;
  int rs = 0;
  int re = m-1;
  int cs = 0;
  int ce = n-1;
  while(cs<=ce && rs <=re){
    for(int i = cs;i<=ce;i++){
      System.out.print(matrix[rs][i] + " ");
    }
    rs++;
    for(int i = rs;i<=re;i++){
      System.out.print(matrix[i][ce] + " ");
    }
    ce--;
    for(int i = ce;i>=cs;i--){
      System.out.print(matrix[re][i] + " ");
    }
    re--;
    for(int i = re;i>=rs;i--){
      System.out.print(matrix[i][cs] + " ");
      
    }
    cs++;
  }

}

}

Check This
It has no extra space used

Cool !! Nice thinking ๐Ÿ˜‰