Created
May 22, 2014 00:44
-
-
Save Cee/1e1c18a3945616119081 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
哈哈别忘了考虑[]
matrix[0].length 存在的条件是matrix.length != 0~