Skip to content

Instantly share code, notes, and snippets.

@Cee
Created May 22, 2014 00:44
Show Gist options
  • Save Cee/1e1c18a3945616119081 to your computer and use it in GitHub Desktop.
Save Cee/1e1c18a3945616119081 to your computer and use it in GitHub Desktop.
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> ret = new ArrayList<Integer>();
int m = matrix.length;
if (m == 0) return ret;
int n = matrix[0].length;
int i = 0;
int j = 0;
int count = 0;
int way = 1; // 1 right 2 down 3 left 4 right
while (count < m * n){
count++;
ret.add(matrix[i][j]);
matrix[i][j] = 0;
if (way == 1){
if ((j + 1 < n) && (matrix[i][j + 1] != 0)){
j++;
} else {
way = 2;
i++;
}
}else if (way == 2){
if ((i + 1 < m) && (matrix[i + 1][j] != 0)){
i++;
} else {
way = 3;
j--;
}
}else if (way == 3){
if ((j - 1 >= 0) && (matrix[i][j - 1] != 0)){
j--;
} else {
way = 4;
i--;
}
}else if (way == 4){
if ((i - 1 >= 0) && (matrix[i - 1][j] != 0)){
i--;
} else {
way = 1;
j++;
}
}
}
return ret;
}
}
@Cee
Copy link
Author

Cee commented May 22, 2014

哈哈别忘了考虑[]
matrix[0].length 存在的条件是matrix.length != 0~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment