Fill the Landlocked Ponds
Medium · Graphs, BFS & DFS · about 20 min
A town map is a grid: 1 is water and 0 is land. Water cells that touch up, down, left or right belong to the same pond (diagonals do not join). A pond that has at least one cell on the edge of the map drains away to a river and is kept. Every other pond is landlocked, and the town fills it in: all of its cells become 0.
Return the map after all landlocked ponds are filled. You may change the input grid.
Example:
fill_landlocked_water([[0, 0, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0], [0, 1, 0, 0]]) → [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 1, 0, 0]]
Hints
- Deciding pond by pond is fiddly. Ask instead: which water can be reached from the edge?
- Start a search from every water cell in the first and last row and the first and last column, and mark all the water it reaches.
- Finally, turn every unmarked water cell into land.
Learn the pattern first: the Graphs, BFS & DFS lesson.
More Graphs, BFS & DFS problems
- Repaint Connected Tiles (Easy)
- Largest Crop Field (Easy)
- Can the Van Get There? (Easy)
- Mold on the Bakery Shelf (Medium)
- Steps to the Nearest Fire Exit (Medium)
- Rain That Reaches Both Coasts (Medium)
- Copy a Network With New Labels (Medium)
- Shortest Clear Path for a Rover (Hard)
- Code Word Relay (Hard)