Final challenge: islands and mazes
After this: Count islands, finish the flood fill, and find the shortest way out of a maze.
This challenge has two classic problems, split into four steps. Each step is scored on its own.
The first problem is a grid of land and water. You count the islands by hand, and then you complete the flood fill that counts them in code. The second problem is a maze. You choose the walk that finds the fewest moves, and then you count the moves.
You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 4Count the islands
Count the islands
1 is land and 0 is water. Land cells that share a side belong to the same island. How many islands are there?
1 1 0 00 1 0 11 0 0 10 0 1 0Finish the flood fill
sink is a depth-first walk over the grid. Complete the line that marks the current cell as visited, so that the four recursive calls cannot come back to it.
def num_islands(grid): rows, cols = len(grid), len(grid[0])
def sink(r, c): if r < 0 or r >= rows or c < 0 or c >= cols or grid[r][c] != "1": return ________________________ # ← mark the cell visited, so the next line cannot loop back to it sink(r + 1, c) sink(r - 1, c) sink(r, c + 1) sink(r, c - 1)
count = 0 for r in range(rows): for c in range(cols): if grid[r][c] == "1": count += 1 sink(r, c) return countstatic int numIslands(char[][] grid) { int count = 0; for (int r = 0; r < grid.length; r++) { for (int c = 0; c < grid[0].length; c++) { if (grid[r][c] == '1') { count++; sink(grid, r, c); } } } return count;}
static void sink(char[][] grid, int r, int c) { if (r < 0 || r >= grid.length || c < 0 || c >= grid[0].length || grid[r][c] != '1') return; ________________________ // ← mark the cell visited, so the next line cannot loop back to it sink(grid, r + 1, c); sink(grid, r - 1, c); sink(grid, r, c + 1); sink(grid, r, c - 1);}Pick the algorithm
You go from S to E through open cells, moving up, down, left or right, and # is a wall. You want the fewest moves. Which walk should you use, and why?
S . . . .# # # # .. . . . .. # # # #E . . . .Count the moves
Same maze. How many moves from S at (0, 0) to E at (4, 0)?
S . . . .# # # # .. . . . .. # # # #E . . . .- Count islands on a grid, finish the flood fill, and find the fewest moves through a maze with breadth-first search.