forked from strivedi4u/hacktoberfest2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spiral matrix problem
58 lines (50 loc) · 1.43 KB
/
Spiral matrix problem
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Scanner;
public class SpiralMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the matrix: ");
int n = sc.nextInt();
int[][] spiralMatrix = generateSpiralMatrix(n);
printMatrix(spiralMatrix);
}
public static int[][] generateSpiralMatrix(int n) {
int[][] matrix = new int[n][n];
int value = 1;
int top = 0;
int bottom = n - 1;
int left = 0;
int right = n - 1;
while (value <= n * n) {
for (int i = left; i <= right; i++) {
matrix[top][i] = value++;
}
top++;
for (int i = top; i <= bottom; i++) {
matrix[i][right] = value++;
}
right--;
for (int i = right; i >= left; i--) {
matrix[bottom][i] = value++;
}
bottom--;
for (int i = bottom; i >= top; i--) {
matrix[i][left] = value++;
}
left++;
}
return matrix;
}
public static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int val : row) {
System.out.printf("%4d", val);
}
System.out.println();
}
}
}
//Output :
/* 1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7 */