LeetCode in Kotlin

3417. Zigzag Grid Traversal With Skip

Easy

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:

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:

Example 2:

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

Output: [2,1,2]

Explanation:

Example 3:

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

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

Explanation:

Constraints:

Solution

class Solution {
    fun zigzagTraversal(grid: Array<IntArray>): List<Int> {
        val ans: MutableList<Int> = ArrayList<Int>()
        val m = grid.size
        val n = grid[0].size
        var i = 0
        var flag = true
        var skip = false
        while (i < m) {
            if (flag) {
                for (j in 0..<n) {
                    if (!skip) {
                        ans.add(grid[i][j])
                    }
                    skip = !skip
                }
            } else {
                for (j in n - 1 downTo 0) {
                    if (!skip) {
                        ans.add(grid[i][j])
                    }
                    skip = !skip
                }
            }
            flag = !flag
            i++
        }
        return ans
    }
}