From e65e91cb5df8d63e2c1a24a692c506b64858228b Mon Sep 17 00:00:00 2001 From: Danial Goodwin Date: Thu, 10 Nov 2016 20:45:35 -0500 Subject: [PATCH] Add Java snippet to print spiral of 2d array --- .gitignore | 1 + language/java/snippet/PrintSpiral.java | 33 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 language/java/snippet/PrintSpiral.java diff --git a/.gitignore b/.gitignore index d48dd10..cea430d 100644 --- a/.gitignore +++ b/.gitignore @@ -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/ diff --git a/language/java/snippet/PrintSpiral.java b/language/java/snippet/PrintSpiral.java new file mode 100644 index 0000000..4cc24ed --- /dev/null +++ b/language/java/snippet/PrintSpiral.java @@ -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(); + } + +}