-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralMatrix.java
More file actions
43 lines (31 loc) · 1.18 KB
/
Copy pathSpiralMatrix.java
File metadata and controls
43 lines (31 loc) · 1.18 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
public class Main
{
public static void main(String[] args) {
int a[][] = { { 1, 2, 3, 4 },
{ 14, 15, 16, 5 },
{ 13, 20, 17, 6 },
{ 12, 19, 18, 7 },
{ 11, 10, 9, 8 }};
int rowStart = 0, rowEnd = a.length;
int colStart = 0, colEnd = a[0].length;
while(rowStart < rowEnd && colStart < colEnd)
{
//print top row (left to right)
for(int i= colStart;i<colEnd;i++)
System.out.print(a[rowStart][i]+ " ");
rowStart+=1;
//print right column (top to bottom)
for(int i=rowStart;i<rowEnd;i++)
System.out.print(a[i][colEnd - 1] + " ");
colEnd-=1;
// print bottom row (right to left)
for(int i = colEnd - 1;i >= colStart;i--)
System.out.print(a[rowEnd - 1][i] + " ");
rowEnd-=1;
// print left column (bottom to top)
for(int i = rowEnd - 1;i >= rowStart;i--)
System.out.print(a[i][colStart]+ " ");
colStart+=1;
}
}
}