-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathDiagonal Traverse of Matrix.cpp
More file actions
62 lines (62 loc) · 1.61 KB
/
Diagonal Traverse of Matrix.cpp
File metadata and controls
62 lines (62 loc) · 1.61 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
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
vector<int> ans;
int m=mat.size();
int n=mat[0].size();
int cnt=0;
//traverse rows
for(int col=0 ; col<n ; col++){
int i=0,j=col;
if(cnt%2==0){
//bottom to top
stack<int> st;
while(i<m && j>=0){
st.push(mat[i][j]);
i++;
j--;
}
while(!st.empty()){
ans.push_back(st.top());
st.pop();
}
}
else{
//top to bottom
while(i<m && j>=0){
ans.push_back(mat[i][j]);
i++;
j--;
}
}
cnt++;
}
//traverse columns
for(int rows=1 ; rows<m ; rows++){
int i=rows,j=n-1;
if(cnt%2==0){
//bottom to top
stack<int> st;
while(i<m && j>=0){
st.push(mat[i][j]);
i++;
j--;
}
while(!st.empty()){
ans.push_back(st.top());
st.pop();
}
}
else{
//top to bottom
while(i<m && j>=0){
ans.push_back(mat[i][j]);
i++;
j--;
}
}
cnt++;
}
return ans;
}
};