|
| 1 | +public class SpiralPattern { |
| 2 | + |
| 3 | + public static void generateSpiralPattern(int n) { |
| 4 | + // Initialize an empty matrix |
| 5 | + int[][] spiralMatrix = new int[n][n]; |
| 6 | + |
| 7 | + // Define directions for right, down, left, and up movements |
| 8 | + int[][] directions = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; |
| 9 | + int currentDirection = 0; |
| 10 | + |
| 11 | + int row = 0, col = 0; // Start from the top-left corner |
| 12 | + for (int num = 1; num <= n * n; num++) { |
| 13 | + // Assign the current number to the matrix |
| 14 | + spiralMatrix[row][col] = num; |
| 15 | + |
| 16 | + // Calculate the next position |
| 17 | + int nextRow = row + directions[currentDirection][0]; |
| 18 | + int nextCol = col + directions[currentDirection][1]; |
| 19 | + |
| 20 | + // Check if we need to change direction |
| 21 | + if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || spiralMatrix[nextRow][nextCol] != 0) { |
| 22 | + // Change direction |
| 23 | + currentDirection = (currentDirection + 1) % 4; |
| 24 | + nextRow = row + directions[currentDirection][0]; |
| 25 | + nextCol = col + directions[currentDirection][1]; |
| 26 | + } |
| 27 | + |
| 28 | + // Move to the next cell |
| 29 | + row = nextRow; |
| 30 | + col = nextCol; |
| 31 | + } |
| 32 | + |
| 33 | + // Print the spiral pattern |
| 34 | + for (int[] rows : spiralMatrix) { |
| 35 | + for (int num : rows) { |
| 36 | + System.out.printf("%02d ", num); // Format numbers as 2 digits |
| 37 | + } |
| 38 | + System.out.println(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public static void main(String[] args) { |
| 43 | + int n = 5; // Set the size of the spiral matrix |
| 44 | + generateSpiralPattern(n); |
| 45 | + } |
| 46 | +} |
0 commit comments