How to print snake pattern in Java

0

 Printing the snake pattern in matrix is one of the basic problems . In various companies this question is asked how can you print the Snake pattern  . Look the image below , this is how a snake pattern look.

First of all we traverse the row from left to right , but second time we traverse the row from right to left. Then left to right and we keep doing this until we traverse each row .

So we have implemented a java code to do this task.


public class Matrix
{

    public static void SnakePattern(int [][] mat)
    {
        for(int i=0;i<mat.length;i++)
        {
            if(i%2==0)
            {
                for(int j=0;j<mat[i].length;j++)
                {
                    System.out.print(mat[i][j]+" ");
                }
            }
            else{
                for(int j=mat[i].length-1;j>=0;j--)
                {
                    System.out.print(mat[i][j]+" ");
                }
            }
            System.out.println();
        }
    }
    public static void main(String [] args)
    {
        int [][] mat = { {1,2,3,4},{3,4,5},{7,5,2,0},{9,4,6,5,1,3}};
        SnakePattern(mat);
    }
}



Output  : 1,2,3,4,5,4,3,7,5,2,0,3,1,5,6,4,9

Time Complexity : O(n^2)

Space Complexity : O(1)



Post a Comment

0Comments
Post a Comment (0)

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

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