码迷,mamicode.com
首页 > 其他好文 > 详细

498. Diagonal Traverse

时间:2020-02-06 10:46:38      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:new   exp   img   etc   ati   result   find   color   ret   

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:

技术图片

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.

 

Time complexity: O(m * n), m = number of rows, n = number of columns.
Space complexity: O(1).

 1 public class Solution {
 2     public int[] findDiagonalOrder(int[][] matrix) {
 3         if (matrix == null || matrix.length == 0) return new int[0];
 4         int m = matrix.length, n = matrix[0].length;
 5         
 6         int[] result = new int[m * n];
 7         int row = 0, col = 0, d = 0;
 8         int[][] dirs = {{-1, 1}, {1, -1}};
 9         
10         for (int i = 0; i < m * n; i++) {
11             result[i] = matrix[row][col];
12             row += dirs[d][0];
13             col += dirs[d][1];
14             
15             if (row >= m) { row = m - 1; col += 2; d = 1 - d;}
16             if (col >= n) { col = n - 1; row += 2; d = 1 - d;}
17             if (row < 0)  { row = 0; d = 1 - d;}
18             if (col < 0)  { col = 0; d = 1 - d;}
19         }
20         
21         return result;
22     }
23 }

 

498. Diagonal Traverse

标签:new   exp   img   etc   ati   result   find   color   ret   

原文地址:https://www.cnblogs.com/beiyeqingteng/p/12267547.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!