Given a matrix of M x N elements (M rows, N columns), return all elements of the matrix in diagonal order as shown in the below image.
Example:
Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,4,7,5,3,6,8,9] Explanation:
Note:
The total number of elements of the given matrix will not exceed 10,000.
public int[] findDiagonalOrder(int[][] matrix) { if (matrix == null || matrix.length == 0) return new int[0]; int row = 0, col = 0, pos = 0, m = matrix.length, n=matrix[0].length, output [] = new int[m * n]; for (pos = 0; pos < m * n; pos++) { output[pos] = matrix[row][col]; if ((row + col) % 2 == 0) { // The direction is always up when the sum of row & col is even // For last column, go down if (col == n-1) { row++; } // For first row & non-last columns, go right else if (row == 0) { col++; } // For not first row & non-last columns, go up and to the right else { row--; col++; } } else { // The direction is always down when the sum of row & col is odd // For last row, go right if (row == m-1) { col++; } // For non-last row & first column, go down else if (col == 0) { row++; } // For non-last row & non-first column, go down and to the left else { row++; col--; } } }
https://leetcode.com/problems/diagonal-traverse/discuss/97711/Java-15-lines-without-using-boolean
通过观察发现 i + j % 2 == 0时是往右上走,其中有两个边界条件,1.到最右列时要往下走,2. 在第一行时往右, 3.一般情况,向右上走
i + j % 2 != 0时往坐下走,也有两个边界条件,1. 到最后一行时往右走,2. 在第一列时往下走,3.一般情况,往左下走
下面还有为什么先判断行/列边界条件,而且if else语句顺序不能变
you will get IndexOutBound Error. The reason is following:
there will be a situation when we satisfy both these two statements, in case i, it is at right top corner, in this case, we can only goes down -- thus it has to first goto "col == n-1" check. Otherwise if goes to "row == 0" check we will have indexOutOfBound error since we can't do col++;
Similarly, there will be a situation when we satisfy both these two statements, in case ii, it is at left bottom corner, in this case, we can only goes right --it has to first goto "row == m-1" check, Otherwise if goes to "col == 0" check we will have indexOutOfBound error since we can't do row++;