Java Program to Print Spiral Pattern of Numbers
Introduction:
When creating a spiral pattern, one arranges numerals in a way that radiates outward in a clockwise or anticlockwise direction from the centre of a grid. As the numerals extend further away from the centre, they take on a spiral shape.
Problem Statement:
The task is to write a Java program that generates a spiral pattern of numbers. The programme should output the pattern as a 2D array and accept an input parameter 'n' that sets the pattern's size.
The square matrix forming the spiral pattern is 'n x n' in size. The design spirals outward in a clockwise direction from the matrix's centre. The initial number is positioned in the middle of the matrix, and the following numbers are positioned all around it, spiralling outward in a circular pattern.
Example:
12345 161718196 152425207 142322218 131211109
Implementation:
Approach 1: Using Single Array
ALGORITHM:
Step 1: Take input from user for the size of the pattern.
Step 2: Create a single array of size n x n.
Step 3: Fill the array in a spiral pattern using four nested loops.
Step 4: Loop 1: Fill the top row of the array from colStart to colEnd.
Step 5: Loop 2: Fill the right column of the array from rowStart to rowEnd.
Step 6: Loop 3: Fill the bottom row of the array from colEnd to colStart.
Step 7: Loop 4: Fill the left column of the array from rowEnd to rowStart.
Sep 8: After each loop iteration, rowStart, rowEnd, colStart, and colEnd are increased or decreased.
Step 9: Till the array is filled with all its elements, repeat steps 4 through 8.
Step 10: The array should be printed spirally.
FileName: SpiralPattern1.java
import java.util.*; public class SpiralPattern1 { public static void main(String[] args) { // Get input from user Scanner sc = new Scanner(System.in); System.out.print("Enter size of the pattern: "); int n = sc.nextInt(); // Create single array of size n x n int[] spiral = new int[n * n]; // Fill the array in spiral pattern int num = 1; int rowStart = 0, rowEnd = n - 1; int colStart = 0, colEnd = n - 1; int index = 0; while (num <= n * n) { // Fill top row for (int i = colStart; i <= colEnd; i++) { spiral[rowStart * n + i] = num++; } rowStart++; // Fill right column for (int i = rowStart; i <= rowEnd; i++) { spiral[i * n + colEnd] = num++; } colEnd--; // Fill bottom row for (int i = colEnd; i >= colStart; i--) { spiral[rowEnd * n + i] = num++; } rowEnd--; // Fill left column for (int i = rowEnd; i >= rowStart; i--) { spiral[i * n + colStart] = num++; } colStart++; } // Print the spiral pattern for (int i = 0; i < n * n; i++) { System.out.print(spiral[i] + "\t"); if ((i + 1) % n == 0) { System.out.println(); } } } }
Output:
Enter size of the pattern: 5 12345 161718196 152425207 142322218 131211109
Complexity Analysis:
Time Complexity: Due to the usage of nested loops to fill the array in a spiral pattern, this programme has an O(n^2) time complexity. The temporal complexity is n x n = n^2 since both the outer and inner loops run n times.
Space Complexity: Because this programme constructs a single array of size n × n to hold the spiral pattern's components, its space complexity is O(n^2).
Approach 2: Using 2D Array
ALGORITHM:
Step 1: Start the program
Step 2: Obtain the user's input on the pattern's size (n).
Step 3: To hold the spiral pattern, create a 2D array of size n x n.
Step 4: Give the values 1, 0, n-1, 0, and n-1 for the variables num, rowStart, rowEnd, colStart, and colEnd, respectively.
Step 5: Repeat steps 6 through 14 until num is less than or equal to n*n:
Step 6: Using a for loop with a variable named i iterating from colStart to colEnd, fill the top row of the array with values ranging from num to n. Set num to spiral[rowStart][i] then raise num by 1.
Step 7: Row increase Begin with 1.
Step 8: Using a for loop with a variable named i that iterates from rowStart to rowEnd, fill the right column of the array with values ranging from num to n. Set num to spiral[i][colEnd] then raise num by 1.
Step 9: ColEnd is decreased by 1.
Step 10: Using a for loop with a variable named i iterating from colEnd to colStart, fill the bottom row of the array with values from num to n. Set num to spiral[rowEnd][i] and add 1 to num.
Step 11: rowEnd is increased by 1.
Step 12: Using a for loop with a variable named i that iterates from rowEnd to rowStart, fill the left column of the array with values ranging from num to n. Set num to spiral[i][colStart] and add 1 to num.
Step 13: Increment colStart by 1.
Step 14: End the while loop.
Step 15: Print the spiral pattern stored in the 2D array, by using two nested for loops to iterate through the rows and columns of the array, and printing the value at each index with a tab delimiter.
Step 16: End the program.
FileName: SpiralPattern2.java
import java.util.*; public class SpiralPattern2 { public static void main(String[] args) { // Get input from user Scanner sc = new Scanner(System.in); System.out.print("Enter size of the pattern: "); int n = sc.nextInt(); // Create 2D array of size n x n int[][] spiral = new int[n][n]; // Fill the array in spiral pattern int num = 1; int rowStart = 0, rowEnd = n - 1; int colStart = 0, colEnd = n - 1; while (num <= n * n) { // Fill top row for (int i = colStart; i <= colEnd; i++) { spiral[rowStart][i] = num++; } rowStart++; // Fill right column for (int i = rowStart; i <= rowEnd; i++) { spiral[i][colEnd] = num++; } colEnd--; // Fill bottom row for (int i = colEnd; i >= colStart; i--) { spiral[rowEnd][i] = num++; } rowEnd--; // Fill left column for (int i = rowEnd; i >= rowStart; i--) { spiral[i][colStart] = num++; } colStart++; } // Print the spiral pattern for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(spiral[i][j] + "\t"); } System.out.println(); } } }
Output:
Enter size of the pattern: 5 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9
Complexity Analysis:
Time complexity: O(n^2) - The algorithm fills the n x n matrix in a spiral pattern, which takes n^2 iterations.
Space complexity: O(n^2) - The algorithm creates a 2D array of size n x n to store the spiral pattern.
Approach 3: Using Iterative
ALGORITHM:
Step 1: Initialise a 2D array'spiral' of size n x n with all elements set to 0.
Step 2: Set up the variables "rowStart," "rowEnd," "colStart," and "colEnd" to track boundaries and "num," which tracks the value that will go in the following position, as initial values.
Step 3: Set the value of the direction variable to 0.
Step 4: Repeat the loop until the spiral's positions are all filled.
Step 4.1: If "direction" is 0, increase "rowStart" and fill the top row from "colStart" to "colEnd" with values ranging from "num" to "num + (colStart + 1) - 1".
Step 4.2: If 'direction' is 1, increment 'colEnd' and put numbers in the right column from 'rowStart' to 'rowEnd' ranging from 'num' to 'num + (rowEnd - rowStart + 1) - 1'.
Step 4.3: If 'direction' is 2, fill the bottom row from 'colEnd' to 'colStart' with values ranging from 'num' to 'num + (colEnd - colStart + 1) - 1' and decrement 'rowEnd'.
Step 4.4: The left column should be filled with values ranging from "num" to "num + (rowEnd - rowStart + 1) - 1" and "colStart" should be increased if "direction" is 3.
Step 4.5: Change "num" to "num + (n x n) - 1." 'direction' should now read '(direction + 1)% 4'.
Step 5: The'spiral' array's items should be printed in row-major order.
FileName: SpiralPattern3.java
import java.util.*; public class SpiralPattern3 { public static void main(String[] args) { // Get input from user Scanner sc = new Scanner(System.in); System.out.print("Enter size of the pattern: "); int n = sc.nextInt(); // Create 2D array of size n x n int[][] spiral = new int[n][n]; // Initialize variables to keep track of boundaries and direction int rowStart = 0, rowEnd = n - 1, colStart = 0, colEnd = n - 1; int num = 1, direction = 0; // Fill the array in spiral pattern iteratively while (rowStart <= rowEnd && colStart <= colEnd) { // Fill top row if (direction == 0) { for (int i = colStart; i <= colEnd; i++) { spiral[rowStart][i] = num++; } rowStart++; } // Fill right column else if (direction == 1) { for (int i = rowStart; i <= rowEnd; i++) { spiral[i][colEnd] = num++; } colEnd--; } // Fill bottom row else if (direction == 2) { for (int i = colEnd; i >= colStart; i--) { spiral[rowEnd][i] = num++; } rowEnd--; } // Fill left column else if (direction == 3) { for (int i = rowEnd; i >= rowStart; i--) { spiral[i][colStart] = num++; } colStart++; } // Update direction direction = (direction + 1) % 4; } // Print the spiral pattern for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(spiral[i][j] + "\t"); } System.out.println(); } } }
Output:
Enter size of the pattern: 5 12345 161718196 152425207 142322218 131211109
Complexity Analysis:
Time complexity: The algorithm fills each element of the 2D array exactly once. Therefore, the time complexity is O(n^2).
Space complexity: The algorithm uses a 2D array of size n x n to store the spiral pattern. Therefore, the space complexity is O(n^2).
Approach 4: Using Recursion
ALGORITHM:
Step 1: Ask the user to input the size of the pattern.
Step 2: Create a 2D array of size n*n.
Step 3: Fill the array in a spiral pattern recursively using a helper function.
Step 4: The helper function takes the boundaries of the current spiral and fills the four sides in a clockwise order.
Step 5: The base case is when the row or column boundaries overlap, indicating that the spiral is complete.
Step 7: Print the filled 2D array.
FileName: SpiralPattern4.java
import java.util.*; public class SpiralPattern4{ public static void main(String[] args) { // Get input from user Scanner sc = new Scanner(System.in); System.out.print("Enter size of the pattern: "); int n = sc.nextInt(); // Create 2D array of size n x n int[][] spiral = new int[n][n]; // Fill the array in spiral pattern recursively fillSpiral(spiral, 0, n-1, 0, n-1, 1); // Print the spiral pattern for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(spiral[i][j] + "\t"); } System.out.println(); } } public static void fillSpiral(int[][] spiral, int rowStart, int rowEnd, int colStart, int colEnd, int num) { // Base case if (rowStart > rowEnd || colStart > colEnd) { return; } // Fill top row for (int i = colStart; i <= colEnd; i++) { spiral[rowStart][i] = num++; } // Fill right column for (int i = rowStart + 1; i <= rowEnd; i++) { spiral[i][colEnd] = num++; } // Fill bottom row for (int i = colEnd - 1; i >= colStart; i--) { spiral[rowEnd][i] = num++; } // Fill left column for (int i = rowEnd - 1; i > rowStart; i--) { spiral[i][colStart] = num++; } // Recursive call with updated boundaries fillSpiral(spiral, rowStart + 1, rowEnd - 1, colStart + 1, colEnd - 1, num); } }
Output:
Enter size of the pattern: 5 12345 161718196 152425207 142322218 131211109
Complexity Analysis:
Time Complexity: O(n^2)-The algorithm fill each cell of the 2D array once, which takes O(n^2) time.
Space Complexity: O(n^2)-The algorithm uses a 2D array of size n*n to store the spiral pattern, which takes O(n^2) space.