-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspiral.java
More file actions
47 lines (45 loc) · 1.26 KB
/
spiral.java
File metadata and controls
47 lines (45 loc) · 1.26 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
44
45
46
47
public class spiral {
public static void SpiralMatrix(int arr[][])
{
int startRow=0;
int endRow= arr.length -1 ;
int startCol =0;
int endCol= arr[0].length -1;
while(startRow<=endRow && startCol<=endCol)
{
for(int i=startCol;i<=endCol;i++)
{
System.out.print(arr[startRow][i]+" ");
}
for(int j=startRow+1 ;j <=endRow;j++)
{
System.out.print(arr[j][endCol]+" ");
}
for(int i=endCol-1;i>=startCol;i--)
{
if(startRow==endRow)
{
break;
}
System.out.print(arr[endRow][i]+" ");
}
for(int j=endRow-1;j>=startRow+1;j--)
{
if(startCol==endCol)
{
break;
}
System.out.print(arr[j][startCol]+" ");
}
startCol++;
startRow++;
endCol--;
endRow--;
}
System.out.println();
}
public static void main(String[] args) {
int[][] arr = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
SpiralMatrix(arr);
}
}