Created
May 30, 2015 20:22
-
-
Save charlespunk/383d10b5657ea706f803 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 List<Integer> spiralOrder(int[][] matrix) { | |
List<Integer> out = new ArrayList<>(); | |
if (matrix.length == 0) { | |
return out; | |
} | |
int firstRow = 0; | |
int lastRow = matrix.length - 1; | |
int firstColumn = 0; | |
int lastColumn = matrix[0].length - 1; | |
while (firstRow < lastRow && firstColumn < lastColumn) { | |
for (int j = firstColumn; j <= lastColumn; j++) { | |
out.add(matrix[firstRow][j]); | |
} | |
for (int i = firstRow + 1; i <= lastRow; i++) { | |
out.add(matrix[i][lastColumn]); | |
} | |
for (int j = lastColumn - 1; j >= firstColumn; j--) { | |
out.add(matrix[lastRow][j]); | |
} | |
for (int i = lastRow - 1; i > firstRow; i --) { | |
out.add(matrix[i][firstColumn]); | |
} | |
firstRow++; | |
lastRow--; | |
firstColumn++; | |
lastColumn--; | |
} | |
if (firstRow == lastRow) { | |
for (int j = firstColumn; j <= lastColumn; j ++) { | |
out.add(matrix[firstRow][j]); | |
} | |
} else if (firstColumn == lastColumn) { | |
for (int i = firstRow; i <= lastRow; i ++) { | |
out.add(matrix[i][firstColumn]); | |
} | |
} | |
return out; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment