-
Notifications
You must be signed in to change notification settings - Fork 12
/
13.03.2024.cpp
57 lines (48 loc) · 1.44 KB
/
13.03.2024.cpp
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
/*You are required to complete this method */
class Solution{
public:
vector<int> matrixDiagonally(vector<vector<int>>&mat)
{
//Your code here
vector<int>ans;
int row=0, col=0;
int n=mat.size();
while(ans.size()<n*n){
// going upward diagonally till my first row or my last column is reached //
while(row>=0 && col<n){
if(row>=0 && col>=0 && row<n && col<n){
ans.push_back(mat[row][col]);
mat[row][col]=1e9;
}
row--;
col++;
}
if(ans.size()==n*n){
break;
}
row=max(row, 0);
col=min(col, n-1);
while(mat[row][col]==1e9){
row++;
}
// going diagonally downwards
while(col>=0 && row<n){
if(row>=0 && col>=0 && row<n && col<n){
ans.push_back(mat[row][col]);
mat[row][col]=1e9;
}
row++;
col--;
}
if(ans.size()==n*n){
break;
}
row=min(row, n-1);
col=max(col, 0);
while(mat[row][col]==1e9){
col++;
}
}
return ans;
}
};