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:

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 of the given matrix will not exceed 10,000.

Analysis

@fisherlei http://fisherlei.blogspot.com/2017/07/leetcode-diagonal-traverse-solution.html

在上升通道的时候, row = row -1, col = col +1

在下降通道的时候,row = row +1, col = col -1

  1. 如果 col > N, col = N-1, row = row +2;

  2. 如果 row > M, row = M-1. col = col +2;

  3. 如果row < 0, row = 0, 变换通道

  4. 如果col < 0, col = 0, 变换通道

@shawngao

Walk Patterns:

  • If out of bottom border(row>= m) then row = m - 1; col += 2; change walk direction.

  • if out of right border(col >= n) then col = n - 1; row += 2; change walk direction.

  • if out of top border(row < 0) then row = 0; change walk direction.

  • if out of left border(col < 0) then col = 0; change walk direction.

  • Otherwise, just go along with the current direction.

直接模拟扫描过程,分类UP,DOWN的移动方向,再对上下左右边界(以及左下,右上定点)进行判断。

Solution

Intuitive Approach - 模拟移动过程

Reference

http://fisherlei.blogspot.com/2017/07/leetcode-diagonal-traverse-solution.html

https://www.geeksforgeeks.org/zigzag-or-diagonal-traversal-of-matrix/

Last updated

Was this helpful?