Skip to content

Instantly share code, notes, and snippets.

@yaodong
Created August 16, 2018 22:24
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 yaodong/79c9f98ca1b565d865e19d9fc05d9afa to your computer and use it in GitHub Desktop.
Save yaodong/79c9f98ca1b565d865e19d9fc05d9afa to your computer and use it in GitHub Desktop.
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