[LeetCode] Zigzag Grid Traversal With Skip

3417. Zigzag Grid Traversal With Skip

You are given an m x n 2D array grid of positive integers.

Your task is to traverse grid in a zigzag pattern while skipping every alternate cell.

Zigzag pattern traversal is defined as following the below actions:

  • Start at the top-left cell (0, 0).
  • Move right within a row until the end of the row is reached.
  • Drop down to the next row, then traverse left until the beginning of the row is reached.
  • Continue alternating between right and left traversal until every row has been traversed.

Note that you must skip every alternate cell during the traversal.

Return an array of integers result containing, in order, the value of the cells visited during the zigzag traversal with skips.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
vector<int> zigzagTraversal(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size(), idx = 0;
for(int i = 0; i < n; i++) {
for(int j = i & 1 ? m & 1 ? m - 2 : m - 1 : 0; 0 <= j and j < m; j += (i & 1 ? -2 : 2)) {
if(grid[0].size() == idx) grid[0].push_back(0);
grid[0][idx++] = grid[i][j];
}
}
return grid[0];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2025/01/12/PS/LeetCode/zigzag-grid-traversal-with-skip/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.