Skip to content

Instantly share code, notes, and snippets.

@HDegano
Created May 29, 2015 04:39
Show Gist options
  • Save HDegano/5f965414e4b3882bb84e to your computer and use it in GitHub Desktop.
Save HDegano/5f965414e4b3882bb84e to your computer and use it in GitHub Desktop.
Print a matrix on spiral order. Clockwise
public class PrintSpiralMatrix {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> elements = new ArrayList<>();
if (matrix.length == 0) return elements;
int m = matrix.length; //rows
int n = matrix[0].length; //col
int row = 0;
int col = -1; //why?cause we are doing ++col, do the col++ first then a clean up
while (true) {
//walk left to right
for (int i = 0; i < n; i++) {
elements.add(matrix[row][++col]);
}
if (--m == 0) break; //can we print?
//walk top to bottom
for (int i = 0; i < m; i++) {
elements.add(matrix[++row][col]);
}
if (--n == 0) break;
for (int i = 0; i < n; i++) {
elements.add(matrix[row][--col]);
}
if (--m == 0) break;
for (int i = 0; i < m; i++) {
elements.add(matrix[--row][col]);
}
}
return elements;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment