Skip to content

Commit

Permalink
Add Java snippet to print spiral of 2d array
Browse files Browse the repository at this point in the history
  • Loading branch information
danialgoodwin committed Nov 11, 2016
1 parent 784f5bc commit e65e91c
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
#!language/java/project/sa-calculator/
!language/java/snippet/
!language/java/snippet/DoubleBraceInitialization.java
!language/java/snippet/PrintSpiral.java
!language/java/snippet/TwoPlusTwoEqualsFive.java
!language/javascript/
!language/haskell/
Expand Down
33 changes: 33 additions & 0 deletions language/java/snippet/PrintSpiral.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
public class PrintSpiral {

public static void main(String[] args) {
int[][] arr = {{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}};
String spiralOrder = printSpriral(arr);
System.out.println("spiralOrder=" + spiralOrder);
}

public static String printSpriral(int[][] arr) {
int rowMin = 0;
int colMin = 0;
int rowMax = arr.length - 1;
int colMax = arr[0].length - 1;
int direction = 0; // right, down, left, up
StringBuilder sb = new StringBuilder();
for (int row = rowMin, col = colMin; rowMin <= rowMax && colMin <= colMax; ) {
sb.append(arr[row][col]).append(" ");
// Navigate direction.
switch (direction) {
case 0: if (col < colMax) { col++; } else { direction = 1; row++; rowMin++; } break;
case 1: if (row < rowMax) { row++; } else { direction = 2; col--; colMax--; } break;
case 2: if (col > colMin) { col--; } else { direction = 3; row--; rowMax--; } break;
case 3: if (row > rowMin) { row--; } else { direction = 0; col++; colMin++; } break;
}
}
return sb.toString();
}

}

0 comments on commit e65e91c

Please sign in to comment.