Rising tide crossing
MediumOnline Assessment
For each trip request, find the lowest tide level at which a flat boat can make the trip across a marsh.
A marsh is a grid of cells. The string rows[r] describes row r, and the letter rows[r][c] gives the ground height of that cell: "a" is height 0, "b" is 1, and so on up to "z" which is 25. When the tide is at level L, every cell whose height is at most L is under water and a boat can sit in it; every other cell is dry ground the boat cannot enter. The tide level is a whole number, and the boat moves between cells that share an edge (up, down, left, right; no diagonals) as long as every cell it enters is under water.
A trip request [r1, c1, r2, c2] asks for the smallest tide level L (a whole number from 0 to 25) at which a boat can get from cell (r1, c1) to cell (r2, c2). Both the starting cell and the destination cell must themselves be under water, so a trip that starts and ends in the same cell needs a level at least as high as that cell. Every cell is under water at level 25, so an answer always exists.
Input:
rows: a non-empty list of equal-length strings of lowercase letters.trips: a list of[r1, c1, r2, c2]requests (possibly empty). All coordinates are inside the grid.
Output: a list of integers, one per request in the order given: the lowest tide level that makes the trip possible.
There can be hundreds of requests on a large marsh, so searching the marsh again for every request will be too slow.
Example 1
- Input:
- [["abc","dbb","eaa"],[[0,0,2,2],[0,2,0,2],[0,0,2,0]]]
- Output:
- [1,2,4]
- Explanation
- The first trip can use the cells
a,b,b,b,athrough the middle of the marsh, so level 1 (b) is enough. The second trip starts and ends in the same cellc, which has height 2, so the boat needs level 2. The third trip ends in the celle(height 4), so no tide below 4 will do even though the route to it is easy.
Example 2
- Input:
- [["aaza","bzza","bbba"],[[0,0,0,3],[0,3,2,0],[0,0,1,1]]]
- Output:
- [1,1,25]
- Explanation
- The direct row between the first two corners is blocked by
zground, but at level 1 the boat can go down the left side, along the bottom row ofbcells and up the right side, so the first two answers are 1. The last trip ends in the middle of thezridge, so it needs level 25.
Example 3
- Input:
- [["cab","bdc","aeb"],[[0,1,2,0],[0,0,0,0],[1,1,2,1],[0,0,2,2]]]
- Output:
- [2,2,4,2]
- Explanation
- The trip from the top middle to the bottom left can go around the left edge through
c,b,a, so level 2 is enough. A same-cell trip needs that cell's own height (cis 2). Reaching theecell in the middle forces level 4 even though the start is only height 3, and the corner-to-corner trip also needs level 2.
Constraints
1 <= rows.length <= 100and1 <= rows[r].length <= 100, all rows the same length- every character of
rowsis a lowercase letter 0 <= trips.length <= 500- all trip coordinates are inside the grid