Skip to content

3417. Zigzag Grid Traversal With Skip 👍

  • Time: O(mn)O(mn)
  • Space: O(mn)O(mn)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  vector<int> zigzagTraversal(vector<vector<int>>& grid) {
    const int m = grid.size();
    const int n = grid[0].size();
    vector<int> ans;
    vector<int> zigzag;

    for (int i = 0; i < m; ++i)
      if (i % 2 == 0) {
        for (int j = 0; j < n; ++j)
          zigzag.push_back(grid[i][j]);
      } else {
        for (int j = n - 1; j >= 0; --j)
          zigzag.push_back(grid[i][j]);
      }

    for (int i = 0; i < zigzag.size(); i += 2)
      ans.push_back(zigzag[i]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public List<Integer> zigzagTraversal(int[][] grid) {
    final int m = grid.length;
    final int n = grid[0].length;
    List<Integer> ans = new ArrayList<>();
    List<Integer> zigzag = new ArrayList<>();

    for (int i = 0; i < m; ++i)
      if (i % 2 == 0) {
        for (int j = 0; j < n; ++j)
          zigzag.add(grid[i][j]);
      } else {
        for (int j = n - 1; j >= 0; --j)
          zigzag.add(grid[i][j]);
      }

    for (int i = 0; i < zigzag.size(); i += 2)
      ans.add(zigzag.get(i));

    return ans;
  }
}
1
2
3
4
class Solution:
  def zigzagTraversal(self, grid: list[list[int]]) -> list[int]:
    zigzag = [row[::-1] if i % 2 else row for i, row in enumerate(grid)]
    return [num for row in zigzag for num in row][::2]
Was this page helpful?