Skip to content

Instantly share code, notes, and snippets.

@film42
Created October 9, 2014 05:40
Show Gist options
  • Save film42/996c2de71b102990cab2 to your computer and use it in GitHub Desktop.
Save film42/996c2de71b102990cab2 to your computer and use it in GitHub Desktop.
I saw someone mention this as a fun problem, so I did it.
public class SpiralMatrix {
public static void spiralPrint( int[][] matrix ) {
int height = matrix.length;
int width = matrix[0].length;
int currCol = 0;
int currRow = 0;
int stopAtRow = height / 2;
if( height % 2 == 1 ) {
stopAtRow = height / 2 + 1;
}
while(currRow < stopAtRow) {
// Across ->
for (int i = currCol; i < width - currCol; ++i) {
System.out.print(matrix[currRow][i] + " ");
}
// Down
for (int i = currRow + 1; i < height - currRow; ++i) {
System.out.print(matrix[i][width - 1 - currCol] + " ");
}
// Across <-
for (int i = width - 2 - currCol; i > currCol; --i) {
System.out.print(matrix[height - 1 - currRow][i] + " ");
}
// Up
for (int i = height - 1 - currRow; i > currCol; --i) {
System.out.print(matrix[i][currCol] + " ");
}
currCol++;
currRow++;
}
}
public static void main(String[] args) {
int[][] matrix = new int[][] {
{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},
};
spiralPrint( matrix );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment