Skip to the code
cf.
+25 XP

#312 Richest Route in a Tile Map

medium

A browser game has a tile map grid of coin values. A tile with 0 is a wall. The player may start on any tile that isn't a wall, then move up, down, left, or right onto tiles that aren't walls, collecting each tile's coins. A tile can't be visited twice, and the player may stop at any time.

Write richestRoute(grid) that returns the most coins the player can collect. If every tile is a wall, return 0.

Example 1

Input: grid = [[0,4,0],[3,9,2],[0,5,0]]
Output: 18

4 → 9 → 5 collects 18. A route can't branch, so it can't reach every arm.

Example 2

Input: grid = [[1,0],[0,1]]
Output: 1

The two coin tiles only touch at a corner, so a route holds one of them.

Constraints

  • 1 <= grid.length, grid[0].length <= 5
  • 0 <= grid[r][c] <= 100
  • At most 20 tiles are not walls.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).