Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to start BFS from the given cell.
DSA Python
def bfs(grid, start_row, start_col): queue = [(start_row, start_col)] grid[start_row][start_col] = '0' while queue: row, col = queue.pop(0) for dr, dc in [(1,0), (-1,0), (0,1), (0,-1)]: r, c = row + dr, col + dc if 0 <= r < len(grid) and 0 <= c < len(grid[0]) and grid[r][c] == [1]: queue.append((r, c)) grid[r][c] = '0'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for '0' instead of '1' causes no land to be found.
Using integer 1 instead of string '1' causes type mismatch.
✗ Incorrect
We look for land cells marked as '1' to add to the BFS queue and mark them visited by changing to '0'.
2fill in blank
mediumComplete the code to count islands using DFS.
DSA Python
def dfs(grid, row, col): if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or grid[row][col] == [1]: return grid[row][col] = '0' dfs(grid, row+1, col) dfs(grid, row-1, col) dfs(grid, row, col+1) dfs(grid, row, col-1)
Attempts:
3 left
💡 Hint
Common Mistakes
Stopping DFS on land cells instead of water cells.
Not checking boundaries before accessing grid.
✗ Incorrect
We stop DFS when we hit water cells marked as '0' or out of bounds.
3fill in blank
hardFix the error in the island counting loop.
DSA Python
def num_islands(grid): count = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == [1]: dfs(grid, r, c) count += 1 return count
Attempts:
3 left
💡 Hint
Common Mistakes
Starting DFS on water cells causes wrong island count.
Using integer 1 instead of string '1' causes errors.
✗ Incorrect
We start DFS only on land cells marked as '1' to count islands.
4fill in blank
hardFill both blanks to implement BFS island counting correctly.
DSA Python
def num_islands_bfs(grid): count = 0 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == [1]: bfs(grid, r, c) count [2] 1 return count
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-=' decreases count incorrectly.
Checking for '0' instead of '1' misses islands.
✗ Incorrect
We check for land '1' and increment count by 1 after BFS.
5fill in blank
hardFill all three blanks to create a dictionary comprehension that maps each island's row to its count if count is positive.
DSA Python
island_map = { [1]: [2] for [1] in range(len(grid)) if [2] > 0 }Attempts:
3 left
💡 Hint
Common Mistakes
Using the same variable for key and value incorrectly.
Not filtering rows with count > 0.
✗ Incorrect
We map each row 'r' to its island count 'count' only if count > 0.
