[AlgoExpert] Zigzag Traverse

Zigzag Traverse

  • Time : O(nm)
  • Space : O(1)
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
#include <vector>

using namespace std;

vector<int> zigzagTraverse(vector<vector<int>> array) {
if(array.empty()) return {};
vector<int> res;
int n = array.size(), m = array[0].size();
int dy = -1, dx = 1, i = 0, j = 0;
while(i != n - 1 or j != m - 1) {
res.push_back(array[i][j]);
if(dy == -1) {
if(i + 1 < n) i += 1;
else j += 1;
while(i and j != m - 1) {
res.push_back(array[i][j]);
i += dy, j += dx;
}
swap(dy, dx);
} else {
if(j + 1 < m) j += 1;
else i += 1;
while(i != n - 1 and j) {
res.push_back(array[i][j]);
i += dy, j += dx;
}
swap(dy, dx);
}
}
res.push_back(array[i][j]);

return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/10/PS/AlgoExpert/zigzag-traverse/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.