Skip to main content

Posts

Featured

Easy trick to solve the Spiral matrix printing problem

Here we have set 4 pointers top, down, left and right and based on iteration we are changing their values. Its very easy if you will work it out then you will definitely understand it. Java code :   class Solution { public List < Integer > spiralOrder ( int [ ] [ ] matrix ) { int top , down , left , right ; top = 0 ; down = matrix . length - 1 ; left = 0 ; right = matrix [ 0 ] . length - 1 ; List < Integer > list = new ArrayList < > ( ) ; int dir = 1 ; while ( top <= down && left <= right ) { if ( dir == 1 ) { for ( int i = top ; i <= right ; i ++ ) list . add ( matrix [ top ] [ i ] ) ; top ++ ; } else if ( dir == 2 ) { for ( int i = top ; i <= down ; i ++ ) list . add ( matrix [ i ] [ right ] ) ; right -- ; } else if ( dir == 3 )

Latest Posts