Created
January 21, 2015 22:51
-
-
Save Maggie199/8df03eff9bf83bdd9c15 to your computer and use it in GitHub Desktop.
Leetcode #54
This file contains 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 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