-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
43 lines (32 loc) · 1.31 KB
/
SpiralMatrix.java
File metadata and controls
43 lines (32 loc) · 1.31 KB
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
package Ds.Achievers;
import java.util.Scanner;
public class SpiralMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("enter number of rows and columns");
int rows = sc.nextInt();
int cols = sc.nextInt();
int[][] matrix = new int[rows][cols];
System.out.println("enter the elements");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
matrix[i][j] = sc.nextInt();
}
}
int rowStart = 0, colStart = 0;
printSpiral(matrix, rowStart, colStart, rows, cols);
}
static void printSpiral(int[][] matrix, int rowStart, int colStart, int rows, int cols){
if (rowStart >= rows || colStart >= cols)
return;
for (int x = rowStart ; x < cols ; x++)
System.out.print(matrix[rowStart][x]+" ");
for (int x = rowStart + 1 ; x < rows ; x++)
System.out.print(matrix[x][cols - 1]+" ");
for (int x = cols - 2 ; x >= colStart ; x--)
System.out.print(matrix[rows - 1][x]+" ");
for (int x = rows - 2 ; x > rowStart ; x--)
System.out.print(matrix[x][colStart]+" ");
printSpiral(matrix, rowStart + 1, colStart + 1, rows - 1, cols - 1);
}
}