LeetCode 498. Diagonal Traverse
题目描述:
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:
1
2
3
4
5
6
7
8
9
10 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.
这道题就是按照题目要求的顺序遍历这个矩阵就可以了。首先有两个方向,对于每个方向在到达矩阵边缘的时候又有两种处理方式,分情况来处理就可以了。 值得注意的是矩阵的右上角与左下角。他们的处理方式分别与矩阵的右边缘和下边缘相同,要注意安排判断横纵坐标的顺序以免越界。
1 | class Solution { |