Instantly share code, notes, and snippets.

Embed
What would you like to do?
import java.util.ArrayList;
public class SpiralMatrix {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
if (matrix == null)
return null;
if (matrix.length == 0)
return new ArrayList<Integer>(); // ask first
int nrows = matrix.length;
int ncols = matrix[0].length;
// get the number of wraps in this matrix
int smaller = nrows < ncols ? nrows : ncols;
int nwraps = (smaller % 2 == 0) ? (smaller / 2) : (smaller / 2 + 1);
ArrayList<Integer> result = new ArrayList<Integer>();
// wrap by wrap, we traverse through this matrix
int l;
int leftStart;
int topStart;
int rightStart;
int bottomStart;
for (l = 0; l < nwraps; l++) {
leftStart = l;
topStart = l;
rightStart = ncols - 1 - l;
bottomStart = nrows - 1 - l;
// from left to right
for (int j = leftStart; j < ncols - 1 - l; j++) {
result.add(matrix[l][j]);
}
// from top to bottom
for (int i = topStart; i < nrows - 1 - l; i++) {
result.add(matrix[i][ncols - 1 - l]);
}
if (topStart == bottomStart) {
// then we are dealing with the same row
// add the last integer and then break;
result.add(matrix[nrows - 1 - l][rightStart]);
break;
}
// from right to left
for (int j = rightStart; j > l; j--) {
result.add(matrix[nrows - 1 - l][j]);
}
if (leftStart == rightStart) {
// then we are dealing with the same column
// add the last integer and then break;
result.add(matrix[bottomStart][l]);
break;
}
// from bottom to top
for (int i = bottomStart; i > l; i--) {
result.add(matrix[i][l]);
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment