Created
August 16, 2018 22:24
-
-
Save yaodong/79c9f98ca1b565d865e19d9fc05d9afa 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
class Solution { | |
public int[] findDiagonalOrder(int[][] matrix) { | |
if (matrix.length == 0) { | |
return new int[0]; | |
} | |
int m = matrix.length, n = matrix[0].length; | |
int[] result = new int[m*n]; | |
int[][] direction = {{-1, 1}, {1, -1}}; | |
int d = 0, j = 0, row = 0, col = 0, rightBound = n - 1, bottomBound = m - 1; | |
while (j < m * n) { | |
result[j++] = matrix[row][col]; | |
if (d == 0) { | |
if (row == 0 || col == rightBound) { | |
d = 1; | |
} | |
if (row == 0 && col == rightBound) { | |
row += 1; | |
continue; | |
} else if (row == 0) { | |
col += 1; | |
continue; | |
} else if (col == rightBound) { | |
row += 1; | |
continue; | |
} | |
} else if (d == 1) { | |
if (col == 0 || row == bottomBound) { | |
d = 0; | |
} | |
if (col == 0 && row == bottomBound) { | |
col += 1; | |
continue; | |
} else if (col == 0) { | |
row += 1; | |
continue; | |
} else if (row == bottomBound) { | |
col += 1; | |
continue; | |
} | |
} | |
row += direction[d][0]; | |
col += direction[d][1]; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment