Q:

Java Program to Print Spiral Pattern

belongs to collection: Java Pattern programs

0

The spiral pattern (or matrix in spiral form) is frequently asked in Java interviews and academics. In this section, we will create a Java program to create a spiral pattern or spiral matrix.

What is Spiral Matrix or Spiral Pattern?

A spiral pattern is a number pattern that can be represented in matrix form. It is made up of a 2D array (m*n). Pattern may represent in two forms, either clockwise or anticlockwise.

In order to print a matrix in spiral pattern (clockwise) form, we need to follow the following traversal order:

  • Left to right (first row)
  • Top to bottom (Last column)
  • Right to left (last row)
  • Bottom to top (First column)

In order to print the spiral pattern (anticlockwise), reverse the above traversal order.

Let's understand the pictorial representation of the spiral patterns, as shown in the following figure.

For example, consider the following 5*5 matrix:

The above matrix can be represented in spiral form as follows:

We can follow any of the approaches to print the spiral pattern:

  • Iterative
  • Recursive

Throughout this section, we have used the iterative approach.

What should be the approach?

  • First, create a 2D array of size n.
  • Declare the variables to store the boundary of the array. Also declare a variable to store the size left to print the spiral.
  • For the movement over the array, use l, r, u, and d letters that represent the direction of movement left, right, up, and down, respectively.
  • Execute a loop from 1 to n*2 to fill the array in spiral form.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Spiral Pattern Java Program

SpiralPaternExample1.java

public class SpiralPatternExample1  
{  
//defining method to print the spiral pattern or matrix  
static void printSpiralPattern(int size)  
{  
//create two variables row and col to traverse rows and columns  
int row = 0, col = 0;  
int boundary = size - 1;  
int sizeLeft = size - 1;  
int flag = 1;  
//variables r, l, u and d are used to determine the movement  
// r = right, l = left, d = down, u = upper  
char move = 'r';  
//creating a 2D array for matrix  
int[][] matrix =new int [size][size];  
for (int i = 1; i < size * size + 1; i++)  
{  
    //assigning values  
    matrix[row][col] = i;  
//switch-case to determine the next index  
switch (move)  
{  
//if right, go right  
case 'r':  
    col += 1;  
    break;  
//if left, go left  
case 'l':  
    col -= 1;  
    break;  
//if up, go up  
case 'u':  
    row -= 1;  
    break;  
//if down, go down  
case 'd':  
    row += 1;  
    break;  
}  
//checks if the matrix has reached the array boundary  
if (i == boundary)  
    {  
        //adds the left size for the next boundary  
        boundary = boundary + sizeLeft;  
        //decrease the size left by 1, if 2 rotations have been made  
        if (flag != 2)  
        {  
        flag = 2;  
        }  
        else  
        {  
        flag = 1;  
        sizeLeft -= 1;  
        }  
        //switch-case to rotate the movement  
        switch (move)  
        {  
        //if right, rotate to down  
        case 'r':  
            move = 'd';  
            break;  
        // if down, rotate to left  
        case 'd':  
            move = 'l';  
            break;  
        // if left, rotate to up  
        case 'l':  
            move = 'u';  
            break;  
        // if up, rotate to right  
        case 'u':  
            move = 'r';  
            break;  
        }  
    }  
    }  
//printing the spiral matrix or pattern  
//outer for loop for rows  
    for (row = 0; row < size; row++)  
    {  
        //inner for loop for columns  
        for (col = 0; col < size; col++)  
            {  
                int n = matrix[row][col];  
                if(n < 10)  
                    System.out.print(n +" ");  
                else  
                    System.out.print(n +" ");  
            }  
        System.out.println();  
    }  
}  
//driver Code  
public static void main(String args[])  
{  
//size of the array?s row and column  
int size = 5;  
System.out.println("Spiral Matrix or Pattern is: \n");  
//calling the method that prints the spiral pattern or matrix   
printSpiralPattern(size);  
}  
}  

Output:

 

Let's see another spiral pattern.

In the following program, we have used the following approach:

Starting the indexing from i = 1 and j = 1. It can be observed that every value of the required matrix will be max(abs(i - n), abs(j - n)) + 1.

SpiralPatternExample2.java

import java.util.Scanner;  
import java.lang.Math;  
public class SpiralPatternExample2  
{  
//function to print the spiral pattern  
public static void printPattern(int n)  
{  
//detrmines the boundary size of the array  
int size = 2 * n - 1;  
//inner loop  
for(int i = 1; i <= size; i++)  
{  
//outer loop      
for(int j = 1; j <= size; j++)  
{  
//calculates and prints the values for pattern  
System.out.print(Math.max(Math.abs(i - n), Math.abs(j - n)) + 1 + " ");  
}  
System.out.println();  
}  
}  
//driver code  
public static void main(String args[])  
{  
Scanner sc = new Scanner(System.in);  
System.out.print("Enter the value of n: ");  
int n = sc.nextInt();  
System.out.println();  
//function calling  
printPattern(n);  
}  
}  

 

Output:

 

SpiralPatternExample3.java

public class SprialPatternExample3  
{  
public static void main(String args[])  
{  
    int SIZE=10;  
    int i, j, N;  
    int[][] board = new int[SIZE][SIZE];  
    int left, top;  
    left = 0;  
    top  = SIZE - 1;  
    N    = 1;  
    for(i=1; i<=SIZE/2; i++, left++, top--)  
    {  
        //fill from left to right  
        for(j=left; j<=top; j++, N++)  
        {  
            board[left][j] = N;  
        }  
        //fill from top to down  
        for(j=left+1; j<=top; j++, N++)  
        {  
            board[j][top] = N;  
        }  
        //fill from right to left  
        for(j=top-1; j>=left; j--, N++)  
        {  
            board[top][j] = N;  
        }  
        //fill from down to top  
        for(j=top-1; j>=left+1; j--, N++)  
        {  
            board[j][left] = N;  
        }  
    }  
    //print the pattern  
    for(i=0; i<SIZE; i++)  
    {  
        for(j=0; j<SIZE; j++)  
        {  
            System.out.printf("%-5d", board[i][j]);  
        }  
    System.out.printf("\n");  
    }  
}  
}  

 

Output:

 

Print a Given Matrix in Spiral Form

There are many approaches that can be used to print a matrix in spiral form.

SpiralToMatrixExample.java

 

import java.io.*;  
public class SpiralToMatrixExample   
{  
//Function print matrix in spiral form  
static void spiralPrint(int m, int n, int a[][])  
{  
int i, k = 0, l = 0;  
/* k - starting row index 
m - ending row index 
l - starting column index 
n - ending column index 
i - iterator 
*/  
while (k < m && l < n)   
{  
//prints the first row from the remaining rows  
for (i = l; i < n; ++i)   
{  
System.out.print(a[k][i] + " ");  
}  
k++;  
  
//prints the last column from the remaining columns  
for (i = k; i < m; ++i)   
{  
System.out.print(a[i][n - 1] + " ");  
}  
n--;  
//prints the last row from the remaining rows   
if (k < m)   
{  
for (i = n - 1; i >= l; --i)   
{  
System.out.print(a[m - 1][i] + " ");  
}  
m--;  
}  
//prints the first column from the remaining columns  
if (l < n)   
{  
for (i = m - 1; i >= k; --i)   
{  
System.out.print(a[i][l] + " ");  
}  
l++;  
}  
}  
}  
//driver Code  
public static void main(String args[])  
{  
int row = 3;  
int col = 6;  
//array to print in spiral form  
int arr[][] = { { 10, 20, 30, 40, 50, 60 }, { 70, 80, 90, 100, 110, 120 }, { 130, 140, 150, 160, 170, 180 } };  
//function Calling  
spiralPrint(row, col, arr);  
}  
} 

Output:

10 20 30 40 50 60 120 180 170 160 150 140 130 70 80 90 100 110

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to print the following pattern... >>