Skip to content

Create Spiral-Matrix.java #6073

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/main/java/com/thealgorithms/misc/Spiral-Matrix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
public class SpiralPattern {

public static void generateSpiralPattern(int n) {
// Initialize an empty matrix
int[][] spiralMatrix = new int[n][n];

// Define directions for right, down, left, and up movements
int[][] directions = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} };
int currentDirection = 0;

int row = 0, col = 0; // Start from the top-left corner
for (int num = 1; num <= n * n; num++) {
// Assign the current number to the matrix
spiralMatrix[row][col] = num;

// Calculate the next position
int nextRow = row + directions[currentDirection][0];
int nextCol = col + directions[currentDirection][1];

// Check if we need to change direction
if (nextRow < 0 || nextRow >= n || nextCol < 0 || nextCol >= n || spiralMatrix[nextRow][nextCol] != 0) {
// Change direction
currentDirection = (currentDirection + 1) % 4;
nextRow = row + directions[currentDirection][0];
nextCol = col + directions[currentDirection][1];
}

// Move to the next cell
row = nextRow;
col = nextCol;
}

// Print the spiral pattern
for (int[] rows : spiralMatrix) {
for (int num : rows) {
System.out.printf("%02d ", num); // Format numbers as 2 digits
}
System.out.println();
}
}

public static void main(String[] args) {
int n = 5; // Set the size of the spiral matrix
generateSpiralPattern(n);
}
}
Loading