Created
May 29, 2015 04:39
-
-
Save HDegano/5f965414e4b3882bb84e to your computer and use it in GitHub Desktop.
Print a matrix on spiral order. Clockwise
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 class PrintSpiralMatrix { | |
public List<Integer> spiralOrder(int[][] matrix) { | |
List<Integer> elements = new ArrayList<>(); | |
if (matrix.length == 0) return elements; | |
int m = matrix.length; //rows | |
int n = matrix[0].length; //col | |
int row = 0; | |
int col = -1; //why?cause we are doing ++col, do the col++ first then a clean up | |
while (true) { | |
//walk left to right | |
for (int i = 0; i < n; i++) { | |
elements.add(matrix[row][++col]); | |
} | |
if (--m == 0) break; //can we print? | |
//walk top to bottom | |
for (int i = 0; i < m; i++) { | |
elements.add(matrix[++row][col]); | |
} | |
if (--n == 0) break; | |
for (int i = 0; i < n; i++) { | |
elements.add(matrix[row][--col]); | |
} | |
if (--m == 0) break; | |
for (int i = 0; i < m; i++) { | |
elements.add(matrix[--row][col]); | |
} | |
} | |
return elements; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment