class Solution {
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
int[][] SPIN = new int[][]{{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int i = 0;
int j = 0;
int index = 0;
int rowE = matrix.length;
if(rowE == 0) {
return result;
}
int colE = matrix[0].length;
if (colE == 1) {
for(int l = 0; l < matrix.length; ++l) {
result.add(matrix[l][0]);
}
return result;
}
int rowS = 1;
int colS = 0;
int total = rowE * colE;
int count = 0;
while (count < total) {
result.add(matrix[i][j]);
i += SPIN[index % 4][0];
j += SPIN[index % 4][1];
count++;
if (i == rowE - 1 && (index % 4 == 1)) {
rowE--;
index++;
} else if (i == rowS && (index % 4 == 3)) {
rowS++;
index++;
}
if (j == colE - 1 && (index % 4 == 0)) {
colE--;
index++;
} else if (j == colS && (index % 4 == 2)) {
colS++;
index++;
}
}
return result;
}
}
My initial thought was setting a "signal" variable and using that to determine the direction our pointer goes and the boundaries of our routes, in a recursive manner. However, that way didn't work, for an additional variable is abundant, and I didn't handle the cases that m may not always equal to n. Then I created a HashSet to avoid duplicate but found out that the order of numbers are completely disturbed when I turned the set to a list. My bad, poor foundation in data structures.
So here I offer the amazing solution whose running time beats 100% and space usage beats 94%.
The bullet points here are:
Look at the SPIN matrix we use to direct the pointers and the count we use to end the iterations. I got there once but messed up with the positions.
This solution dealt with edge cases when it is a vertical one-line matrix!
This solution dealt with the turn-around corners element by element, instead of dealing with them in iteration conditions, and the running time is just O(m*n).
My initial thought was setting a "signal" variable and using that to determine the direction our pointer goes and the boundaries of our routes, in a recursive manner. However, that way didn't work, for an additional variable is abundant, and I didn't handle the cases that m may not always equal to n. Then I created a HashSet to avoid duplicate but found out that the order of numbers are completely disturbed when I turned the set to a list. My bad, poor foundation in data structures. So here I offer the amazing solution whose running time beats 100% and space usage beats 94%. The bullet points here are: