LeetCode 498. diagonal traverse (Java)

498. diagonal traverse

Given a matrix (M rows, N columns) contains M x N elements, all the elements return to the matrix diagonal traversal order, diagonal traverse as shown below.

Example:
Input:
[
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Output: [1,2,4,7,5,3,6,8,9]

Note:
The total number of elements in a given matrix to no more than 100,000.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/diagonal-traverse
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Note: to find the law, pay attention to the direction of the problem

class Solution {
    public int[] findDiagonalOrder(int[][] matrix) {
         if(matrix==null||matrix.length==0)
        {
            return new int[0];
        }
        int M=matrix.length;
        int N=matrix[0].length;
        int[] res=new int[M*N];
        int row=0;
        int column=0;
        int direction=1;
        int r=0;
        while(row<M&&column<N)
        {
            res[r++]=matrix[row][column];//只要给定坐标还在数组中就将该坐标元素加入结果数组中
            //两个坐标,一个加一,一个减一。
            //direction为0,行数加一,列数减一得出的是左下角元素;
            //direction为1,行数减一,列数加一得出的是右上角元素。
            int new_row=row+(direction==1?-1:1);
            int new_column=column+(direction==1?1:-1);
            //判断新坐标是否还在数组内
            if(new_row<0||new_row==M||new_column<0||new_column==N)
            {
                //若新坐标不在数组内,即到达边界
                if(direction==1)
                {
                    //向右找下一行对角线,如果列数没有到达本行的最后一位,则行数不变,列数加一
                    row+=(column==N-1?1:0);
                    column+=(column<N-1?1:0);
                }
                else
                {
                    //向下找下一行对角线,如果行数没有到达本列的最后一位,则列数不变,行数加一
                    column+=(row==M-1?1:0);
                    row+=(row<M-1?1:0);
                }
                //到达边界后要改变方向
                direction=1-direction;
            }
            else
            {
                //如果新坐标还在数组内,证明本行对角线还未读完,继续读即可
                row=new_row;
                column=new_column;
            }
        }
        return res;   
    }
}
Published 88 original articles · won praise 0 · Views 2153

Guess you like

Origin blog.csdn.net/nuts_and_bolts/article/details/105100405