How to print a matrix in spiral pattern in java

0

 

Printing a matrix in spiral form is one of the most asked interview question of all times. In this problem we are given a matrix and we have print it in spiral manner. First we have to print the outer layer then we go inner layer and we keep doing it until we reach the core. This is the basic idea to solve this problem.

Lets assume we are given a 4x4 matrix .


Output : 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10


Explaination : As mentioned earlier first we print the outer layer

ie. 1 then 2 ,3 ,4 ,8 , 12 ,16, 15, 14, 13, 9 ,5

Once we are done with outer layer we will go inside and again print the outer layer for that inner matrix ie. 6 then 7 , 11 and 10


Java Code :



class HindiCodingCommunity{
public static void search(int mat[][])
{
int top=0 ;
int left = 0;
int bottom = mat.length-1;
int right= mat[0].length-1;

while(top<=bottom && left<=right)
{
for(int i=left;i<=right;i++)
System.out.println(mat[top][i]);
top++;

for(int i=top;i<=bottom;i++)
System.out.println(mat[i][right]);
right--;
if(top<=bottom)
{
for(int i=right;i>=left;i--)
System.out.println(mat[bottom][i]);
bottom--;
}
if(left<=right)
{
for(int i=bottom;i>=top;i--)
System.out.println(mat[i][left]);
left++;
}

}

}

public static void main(String args[])
{
int[][] mat= {{3,6,9},{4,7,10},{5,8,11}};
search(mat);
}
}


Output : 3 6 9 10 11 8 5 4 7

Time Complexity : O(R*C)  ; where R is the total number of rows and C is total number of columns.

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !