Diagonal Traverse

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

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.

 1 class Solution {
 2 public:
 3     vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
 4         if(matrix.size() == 0 || matrix[0].size() == 0)
 5             return {};
 6         int n = matrix[0].size(), m = matrix.size();
 7         
 8         vector<int> res;
 9         for(int i = 0; i < m + n - 1; i++)
10         {
11             int begin_pos = res.size();
12             for(int row = max(0, i-n+1),  col = min(i, n-1); col >= 0 && row < m; row++, col--)
13                 res.push_back(matrix[row][col]);
14             if(i % 2 == 0)
15                 reverse(res.begin() + begin_pos, res.end());
16         }
17         return res;
18     }
19 };

猜你喜欢

转载自www.cnblogs.com/cccv/p/9197471.html