Skip to content

Instantly share code, notes, and snippets.

@Maggie199
Created January 21, 2015 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Maggie199/8df03eff9bf83bdd9c15 to your computer and use it in GitHub Desktop.
Save Maggie199/8df03eff9bf83bdd9c15 to your computer and use it in GitHub Desktop.
Leetcode #54
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0)
return result;
int endy=matrix.length;
int endx=matrix[0].length;
int starty = 0;
int startx = 0;
while(startx!=endx && starty!=endy){
if(starty < endy){
for(int i=startx;i<endx;i++){
result.add(matrix[starty][i]);
}
starty++;
}
if(startx < endx){
for(int i=starty;i<endy;i++){
result.add(matrix[i][endx-1]);
}
endx--;
}
if(starty < endy){
for(int i=endx-1; i>=startx;i--){
result.add(matrix[endy-1][i]);
}
endy--;
}
if(startx < endx){
for(int i=endy-1;i>=starty;i--){
result.add(matrix[i][startx]);
}
startx++;
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment