Complete the code to start BFS from the given cell.
function bfs(grid, row, col, visited) {
const queue = [];
queue.push([row, col]);
visited[row][col] = [1];
while (queue.length > 0) {
const [r, c] = queue.shift();
// BFS logic here
}
}We mark the starting cell as visited by setting visited[row][col] to true.
Complete the code to check if a cell is within grid bounds.
function isValid(grid, row, col) {
return row >= 0 && row < grid.length && col >= 0 && col < [1];
}The number of columns is grid[0].length, so col must be less than this.
Fix the error in the DFS recursive call to explore neighbors.
function dfs(grid, row, col, visited) {
if (!isValid(grid, row, col) || visited[row][col] || grid[row][col] === '0') {
return;
}
visited[row][col] = true;
dfs(grid, row + 1, col, visited);
dfs(grid, row - 1, col, visited);
dfs(grid, row, col + 1, visited);
dfs(grid, row, col [1], visited);
}The last DFS call should explore the left neighbor by decreasing the column index by 1.
Fill both blanks to correctly check neighbors in BFS.
const directions = [[1, 0], [-1, 0], [0, 1], [0, [1]]]; for (const [dr, dc] of directions) { const nr = r + dr; const nc = c + dc; if (isValid(grid, nr, nc) && !visited[nr][nc] && grid[nr][nc] === '1') { queue.push([nr, nc]); visited[nr][nc] = [2]; } }
The last direction is left, so column change is -1. Visited cells are marked true.
Fill both blanks to create a dictionary comprehension that counts islands using DFS.
let count = 0; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[0].length; j++) { if (grid[i][j] === '1' && !visited[i][j]) { [1](grid, i, j, visited); count[2]; } } } return count;;
We call dfs to explore the island, increment count by 1, and return count with a semicolon.
