Skip to content

Instantly share code, notes, and snippets.

@raphaelrk
Created January 6, 2016 23:17
Show Gist options
  • Save raphaelrk/ea2685e90d7072807581 to your computer and use it in GitHub Desktop.
Save raphaelrk/ea2685e90d7072807581 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.*;
public class Solution {
public static final int RIGHT = 1;
public static final int LEFT = 2;
public static final int DOWN = 3;
public static final int UP = 4;
/**
* This method should print a 2D integer array in spiral order, clockwise
*
* @param matrix 2D array of integers to traverse over
*
*/
public static void spiralTraverse(int matrix[][]) {
int colLen = matrix[0].length;
int rowLen = matrix.length;
int row = 0;
int col = 0;
boolean traversing = true;
int dir = RIGHT;
int colMinBound = -1, colMaxBound = colLen,
rowMinBound = -1, rowMaxBound = rowLen;
System.out.println(matrix[row][col]);
int newCol = col + (dir == RIGHT ? 1 : 0) - (dir == LEFT ? 1 : 0);
int newRow = row + (dir == DOWN ? 1 : 0) - (dir == UP ? 1 : 0);
while(traversing) {
if(newCol == colMinBound) { // hit boundary while going left
rowMaxBound = row;
dir = UP;
} else if(newCol == colMaxBound) { // hit boundary while going right
rowMinBound = row;
dir = DOWN;
} else if(newRow == rowMinBound) { // hit boundary while going up
colMinBound = col;
dir = RIGHT;
} else if(newRow == rowMaxBound) { // hit boundary while going down
colMaxBound = col;
dir = LEFT;
} else {
col = newCol;
row = newRow;
System.out.println(matrix[row][col]);
}
newCol = col + (dir == RIGHT ? 1 : 0) - (dir == LEFT ? 1 : 0);
newRow = row + (dir == DOWN ? 1 : 0) - (dir == UP ? 1 : 0);
// detect if spiral traveral is finished-
// if difference between boundries is 1, nowwhere to go
if(rowMaxBound - rowMinBound == 1 || colMaxBound - colMinBound == 1){
traversing = false;
}
}
}
public static void main(String[] args) {
// int EXAMPLE_MATRIX[][] = { {1,2,3}, {4,5,6}, {7,8,9} };
// int EXAMPLE_MATRIX[][] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} };
int EXAMPLE_MATRIX[][] = { {1, 2}, {3, 4}, {5, 6}, {7, 8} };
spiralTraverse(EXAMPLE_MATRIX);
}
}
/*
[
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9,10,11,12],
[13,14,15,16]
]
[
[ 1, 2, 3, 4, 0, 0],
[ 5, 6, 7, 8, 0, 0],
[ 9,10,11,12, 0, 0],
[13,14,15,16, 0, 0],
[13,14,15,16, 0, 0],
[13,14,15,16, 0, 0]
]
*/
// row 0 col 9
// row 1 col 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment