-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path25_Diagonal_Traverse.cpp
More file actions
70 lines (55 loc) · 1.38 KB
/
Copy path25_Diagonal_Traverse.cpp
File metadata and controls
70 lines (55 loc) · 1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// 498. Diagonal Traverse
// Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order.
// Example 1:
// Input: mat = [[1,2,3],[4,5,6],[7,8,9]]
// Output: [1,2,4,7,5,3,6,8,9]
// Example 2:
// Input: mat = [[1,2],[3,4]]
// Output: [1,2,3,4]
// Constraints:
// m == mat.length
// n == mat[i].length
// 1 <= m, n <= 104
// 1 <= m * n <= 104
// -105 <= mat[i][j] <= 105
class Solution
{
public:
vector<int> findDiagonalOrder(vector<vector<int>> &matrix)
{
if (matrix.empty() || matrix[0].empty())
return {};
int m = matrix.size(), n = matrix[0].size();
vector<int> result(m * n);
int row = 0, col = 0;
for (int i = 0; i < m * n; i++)
{
result[i] = matrix[row][col];
if ((row + col) % 2 == 0)
{
if (col == n - 1)
row++;
else if (row == 0)
col++;
else
{
row--;
col++;
}
}
else
{
if (row == m - 1)
col++;
else if (col == 0)
row++;
else
{
row++;
col--;
}
}
}
return result;
}
};