forked from davidals/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpiralPrinter.java
More file actions
39 lines (36 loc) · 1.39 KB
/
SpiralPrinter.java
File metadata and controls
39 lines (36 loc) · 1.39 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
public class SpiralPrinter {
public static void print(int[][] matrix){
int lowerI = 0;
int upperI = matrix.length - 1;
int lowerJ = 0;
int upperJ = matrix[0].length - 1;
while(true){
if(canContinue(lowerI, upperI, lowerJ, upperJ)){
for (int j = lowerJ; j <= upperJ; j++)
System.out.print(matrix[lowerI][j] + " ");
lowerI++;
}
if(canContinue(lowerI, upperI, lowerJ, upperJ)){
for(int i = lowerI; i <= upperI; i++)
System.out.print(matrix[i][upperJ] + " ");
upperJ--;
}
if(canContinue(lowerI, upperI, lowerJ, upperJ)){
for(int j = upperJ; j>= lowerJ; j--)
System.out.print(matrix[upperI][j] + " ");
upperI--;
}
if(canContinue(lowerI, upperI, lowerJ, upperJ)){
for(int i = upperI; i>= lowerI; i--)
System.out.print(matrix[i][lowerJ] + " ");
lowerJ++;
}
if(!canContinue(lowerI, upperI, lowerJ, upperJ))
break;
}
System.out.println();
}
private static boolean canContinue(int lowerI, int upperI, int lowerJ, int upperJ) {
return lowerI <= upperI && lowerJ <= upperJ;
}
}