Matrix Spiral Traversing

This post gives solution for 2D Matrix Spiral Traversing .

package testproject;

/**
*
* @author Yogesh
*/
public class SpriralTraverse {

    public static void main(String[] args){
        //Sample Array
        char[][] array = {{'1','2','3','4','5'},
                          {'L','1','2','3','6'},
                          {'K','E','1','4','7'},
                          {'J','D','2','5','8'},
                          {'I','C','3','6','9'},
                          {'H','B','4','7','0'},
                          {'G','A','9','8','A'},
                          {'F','E','D','C','B'}};
       int iEnd = 7;
       int jEnd = 4;
       int iStart =0, jStart=0;
       while(iStart<=iEnd && jStart <=jEnd){
           //Recursing method
           traverse(iStart, jStart, iEnd, jEnd, array);
           iStart++;
           jStart++;
           jEnd = jEnd -1;
           iEnd = iEnd -1;
       }
     }

    public static void traverse(int iStart, int jStart,
                                int iEnd, int jEnd, char[][] array){
       int count = 0;
       int totalCount = 0;
       if(jStart==jEnd){
           totalCount = (iEnd-iStart)+1;
       }else
           totalCount = (((jEnd-jStart)+1)*2)+(((iEnd-iStart)-1)*2);

       int direction =1;
       int ii =iStart;
       int jj =jStart;
       while(count <totalCount) {
           //System.out.print("["+iStart+","+jStart+"] == ");
           //System.out.println(array[iStart][jStart]);
           System.out.print(array[iStart][jStart]+" ");
           if( direction ==1){
               if(jStart<jEnd){
                   jStart++;
               } else if (iStart<iEnd){
                   iStart++;
               }if(jStart==jEnd && iStart == iEnd){
                   direction =-1;
               }
           } else{
               if(jStart>jj){
                   jStart--;
               }else if(iStart>ii+1){
                   iStart--;
               }
           }
       count ++;
       }
   }
}

Here output is

1 2 3 4 5 6 7 8 9 0 A B C D E F G H I J K L 1 2 3 4 5 6 7 8 9 A B C D E 1 2 3 4

Comments

Popular posts from this blog

Composite Design Pattern by example

State Design Pattern by Example

Eclipse command framework core expression: Property tester