498. Diagonal Traverse

Diagonal Traverse

https://www.youtube.com/watch?v=uj65eeIScnQ

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:


class Solution {
    public int[] findDiagonalOrder(int[][] matrix) {
        // sanity check 
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0){
            return new int[0];
        }
        int row = matrix.length;
        int col = matrix[0].length;
        int[] res = new int[row * col];
        int index = 0;
        int numberOfIterations = row + col - 1;
        
        for(int i = 0; i < numberOfIterations; i++){
            if(i % 2 == 0){
                // i is even
                int x = i < row ? i : row - 1;
                int y = i < row ? 0 : i - row + 1;
                while(x >= 0 && y < col){
                    res[index++] = matrix[x--][y++];
                    // index++;
                    // x++;
                    // y++
                }
            }else{
                // i is oadd
                int x = i < col ? 0 : i - col + 1;
                int y = i < col ? i : col - 1;
                while(x < row && y >= 0){
                    res[index++] = matrix[x++][y--];
                }
            }
        }
        return res;

    }
}

// idea: find the starting points for both directions, 
// these two directions can be categorized as one , right up
// another one is left down, 
// the use of index 

 

Example:

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

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

Explanation:

posted on 2018-08-28 21:26  猪猪&#128055;  阅读(106)  评论(0)    收藏  举报

导航