Zigzag Grid Traversal With Skip
Source: leetcode
Difficulty: Easy
Tags: array, matrix, simulation

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.


 


**Example 1:**



**Input:** grid \= \[\[1,2],\[3,4]]


**Output:** \[1,4]


**Explanation:**


**![](https://assets.leetcode.com/uploads/2024/11/23/4012_example0.png)**



**Example 2:**



**Input:** grid \= \[\[2,1],\[2,1],\[2,1]]


**Output:** \[2,1,2]


**Explanation:**


![](https://assets.leetcode.com/uploads/2024/11/23/4012_example1.png)



**Example 3:**



**Input:** grid \= \[\[1,2,3],\[4,5,6],\[7,8,9]]


**Output:** \[1,3,5,7,9]


**Explanation:**


![](https://assets.leetcode.com/uploads/2024/11/23/4012_example2.png)



 


**Constraints:**


- `2 <= n == grid.length <= 50`
- `2 <= m == grid[i].length <= 50`
- `1 <= grid[i][j] <= 2500`




C++ solution:
class Solution {
public:
    vector<int> zigzagTraversal(vector<vector<int>>& grid) {
        vector<int> result;
        bool take = true;
        for (int i = 0; i < grid.size(); i++) {
            if (i % 2 == 0) {
                for (int j = 0; j < grid[i].size(); j++) {
                    if (take) result.push_back(grid[i][j]);
                    take = !take;
                }
            } else {
                for (int j = grid[i].size() - 1; j >= 0; j--) {
                    if (take) result.push_back(grid[i][j]);
                    take = !take;
                }
            }
        }
        return result;
    }
};

Go solution:
func zigzagTraversal(grid [][]int) []int {
	res := []int{}
	count := 0
	n := len(grid)
	m := len(grid[0])
	for i := 0; i < n; i++ {
		if i%2 == 0 {
			for j := 0; j < m; j++ {
				if count%2 == 0 {
					res = append(res, grid[i][j])
				}
				count++
			}
		} else {
			for j := m - 1; j >= 0; j-- {
				if count%2 == 0 {
					res = append(res, grid[i][j])
				}
				count++
			}
		}
	}
	return res
}

Java solution:
class Solution {
    public List<Integer> zigzagTraversal(int[][] grid) {
        List<Integer> res = new ArrayList<>();
        int index = 0;
        for (int i = 0; i < grid.length; i++) {
            if (i % 2 == 0) {
                for (int j = 0; j < grid[i].length; j++) {
                    if (index % 2 == 0)
                        res.add(grid[i][j]);
                    index++;
                }
            } else {
                for (int j = grid[i].length - 1; j >= 0; j--) {
                    if (index % 2 == 0)
                        res.add(grid[i][j]);
                    index++;
                }
            }
        }
        return res;
    }
}

JavaScript solution:
var zigzagTraversal = function(grid) {
    let result = [];
    let count = 0;
    for (let i = 0; i < grid.length; i++) {
        if (i % 2 === 0) {
            for (let j = 0; j < grid[i].length; j++) {
                if (count % 2 === 0) result.push(grid[i][j]);
                count++;
            }
        } else {
            for (let j = grid[i].length - 1; j >= 0; j--) {
                if (count % 2 === 0) result.push(grid[i][j]);
                count++;
            }
        }
    }
    return result;
};

Python solution:
class Solution:
    def zigzagTraversal(self, grid: List[List[int]]) -> List[int]:
        res = []
        pick = True
        for i, row in enumerate(grid):
            if i % 2 == 0:
                for val in row:
                    if pick:
                        res.append(val)
                    pick = not pick
            else:
                for val in row[::-1]:
                    if pick:
                        res.append(val)
                    pick = not pick
        return res

Ruby solution:
def zigzag_traversal(grid)
  cells = []
  grid.each_with_index do |row, i|
    if i.even?
      row.each { |val| cells << val }
    else
      row.reverse.each { |val| cells << val }
    end
  end
  result = []
  cells.each_with_index { |val, i| result << val if i.even? }
  result
end