-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
38 lines (36 loc) · 1.21 KB
/
SpiralMatrix.java
File metadata and controls
38 lines (36 loc) · 1.21 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
public class SpiralMatrix {
public static void spiralMatrixPrint(int rowStart,int rowEnd,int colStart,int colEnd,int[][] arr){
for(int i = rowStart;i <= colEnd;i++){
System.out.print(arr[rowStart][i]+ " ");
}
rowStart++;
for(int i = rowStart;i <=rowEnd;i++ ){
System.out.print(arr[i][colEnd]+ " ");
}
colEnd--;
for(int i = colEnd;i >= colStart;i--){
System.out.print(arr[rowEnd][i]+ " ");
}
rowEnd--;
if(rowStart < rowEnd){
for (int i = rowEnd; i >= rowStart; i--) {
System.out.print(arr[i][colStart] + " ");
}
colStart++;
}
if(rowStart <= rowEnd && colStart <= colEnd){
spiralMatrixPrint(rowStart,rowEnd,colStart,colEnd,arr);
}
}
public static void main(String[] args) {
int[][] arr = {{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}};
int rowStart = 0;
int rowEnd = arr.length - 1;
int colStart = 0;
int colEnd = arr[0].length - 1;
spiralMatrixPrint(rowStart,rowEnd,colStart,colEnd,arr);
}
}