Spiral sprinkler
EasyOnline Assessment
Simulate a garden sprinkler head that sweeps the garden in a spiral and waters the plants it passes.
The garden is a rectangular grid: garden[r][c] is a lowercase letter for a plant (each letter is the plant's name) or . for bare ground. The head starts on the top-left cell, moves right along the top row, and turns clockwise (right, down, left, up) whenever the next cell would be outside the garden or has already been visited. It visits every cell exactly once and stops after the last one.
The tank holds enough water for water plants. Every plant the head reaches while the tank still has water is watered and uses one unit. Bare ground is visited but never uses water. Once the tank is empty the head waters nothing more.
Input: garden, a list of equal-length strings; water, an integer.
Output: a string made of the names of the watered plants, in the order they were watered. If nothing is watered, return "".
Example 1
- Input:
- [["abc","def","ghi"],6]
- Output:
- "abcfih"
- Explanation
- The head visits a, b, c along the top, then f and i down the right side, then h, g along the bottom, d up the left side and finally e in the middle. With water for 6 plants the first six cells are
abcfih.
Example 2
- Input:
- [["ab.d","e.gh","ijkl"],7]
- Output:
- "abdhlkj"
- Explanation
- Spiral order is a, b,
., d, h, l, k, j, i, e,., g. The bare cells are passed over without using water, so the watered plants in order are a, b, d, h, l, k, j: seven plants fill the tank exactly, givingabdhlkj.
Example 3
- Input:
- [["x",".","y","z"],3]
- Output:
- "xyz"
- Explanation
- A single column is a spiral that only goes down: x,
., y, z. The bare cell is skipped and the three plants use the 3 units of water:xyz.
Constraints
1 <= garden.length <= 121 <= garden[i].length <= 12, and every row has the same length- every character of
gardenis.or a lowercase letter 0 <= water <= 144