call(back)
Algorithms & Data StructuresmediumSign in to star problems

Longest Zigzag Path in a Grid

Given a grid of integers, find the longest zigzag path. A path starts at any cell, moves one step at a time to a cell directly above, below, left or right, and never visits a cell twice. Along the path the comparisons between consecutive values must strictly alternate:

a < b > c < d > ...     or     a > b < c > d < ...

Two equal neighbours can never be consecutive on a path. Return the number of cells on the longest zigzag path; a single cell is a path of length 1.

[[1, 5, 2],
 [9, 3, 8]]     ->  6      // 1 < 9 > 3 < 5 > 2 < 8

[[4, 4],
 [4, 4]]        ->  1

The grid has at most 5 rows and 5 columns. The screen opens with a long resume discussion, so get a working search down early and optimise afterwards.

Hints

Hint 1

The state of a partial path is its last cell, whether the next step must go up or down in value, and which cells are already used.

Hint 2

Run a depth-first search from every cell, once starting with an upward step and once with a downward step, marking cells on the way in and unmarking on the way out.

Hint 3

Be careful with memoising on (cell, direction) the way the longest-increasing-path problem does. There, values only rise, so a path can never return to a cell. Here 1 < 9 > 1 would reuse a cell unless the visited set is part of the state.

Topics

Asked at

Similar Problems6