forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
85 lines (67 loc) · 1.64 KB
/
main.cpp
File metadata and controls
85 lines (67 loc) · 1.64 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/// Source : https://leetcode.com/problems/diagonal-traverse/description/
/// Author : liuyubobobo
/// Time : 2018-06-03
#include <iostream>
#include <vector>
using namespace std;
/// Simulation
/// Time Complexity: O(n * m)
/// Space Complexity: O(1)
class Solution {
private:
int n, m;
public:
vector<int> findDiagonalOrder(vector<vector<int>>& matrix) {
vector<int> res;
n = matrix.size();
if(n == 0)
return res;
m = matrix[0].size();
int x = 0, y = 0;
int nextX, nextY;
bool up = true;
while(true){
res.push_back(matrix[x][y]);
if(up)
nextX = x - 1, nextY = y + 1;
else
nextX = x + 1, nextY = y - 1;
if(inArea(nextX, nextY))
x = nextX, y = nextY;
else if(up){
if(inArea(x, y + 1))
y ++;
else
x ++;
up = false;
}
else{
if(inArea(x + 1, y))
x ++;
else
y ++;
up = true;
}
if(!inArea(x, y))
break;
}
return res;
}
private:
bool inArea(int x, int y){
return x >= 0 && x < n && y >= 0 && y < m;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
vector<vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}};
print_vec(Solution().findDiagonalOrder(matrix));
return 0;
}