Ctrl K

Trail With One Bend

Hard
You are given a rectangular grid board where every cell holds 0, 1 or 2. Call a chain of cells a *trail* if: - its first cell holds 1, and the values after it go 2, 0, 2, 0, …; - every next cell is a diagonal neighbour of the previous one (one row and one column away); - the trail starts in one of the four diagonal directions and may turn 90° clockwise at most once, after which it continues straight in the new direction. Return the length of the longest trail, in cells. If the grid has no 1 at all, return 0.
Example 1
board=[[1, 0, 0], [0, 2, 0], [0, 0, 0], [0, 2, 0], [0, 0, 0]] → 5

From the 1 at (0,0) go down-right: 2 at (1,1), 0 at (2,2). Turn clockwise there and go down-left: 2 at (3,1), 0 at (4,0). That is 5 cells.

Example 2
board=[[2, 1], [0, 2]] → 1

The only diagonal neighbour of the 1 is (1,0), which holds 0, while 1 must be followed by 2. The trail is just one cell long.

Example 3
board=[[0, 2], [2, 0]] → 0

There is no 1 to start a trail from.

Constraints
  • 1 ≤ len(board), len(board[0]) ≤ 500
  • All rows have the same length
  • board[i][j] is 0, 1 or 2
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsLongest Uphill Walk HardSix-Cell Tile Slider HardCutting a Berry Cake HardMouse, Cat and Cheese HardUphill-Only Walks Hard
loading Python…
Input
board=[[1, 0, 0], [0, 2, 0], [0, 0, 0], [0, 2, 0], [0, 0, 0]]
Expected
5

Run checks the first 3 tests in your browser. Submit checks all 79 tests on the server, hidden ones included.