<aside> 💡 Start with a cell. Check conditions, process call, search around.
</aside>
General approach:
count = 0;
function dfs(cell) {
// 1. Check conditions
if (cell === 0 || isOutsideGrid()) {
return;
}
// 2. Process cell
count++;
matrix[cell] = 0;
// 3. Search around
dfs(right);
dfs(left);
dfs(top);
dfs(bottom);
}
<aside> 💡 Run DFS on every cell of the grid which is “1”. After DFS, increase count and continue looping.
</aside>
https://leetcode.com/problems/number-of-islands/
function dfs(row, col) {
// 1. Check conditions
if (
row < 0 ||
col < 0 ||
row >= grid.length ||
col >= grid[0].length ||
grid[row][col] === "0"
) {
return;
}
// 2. Process cell
grid[row][col] = "0";
// 3. Search around
dfs(row, col + 1);
dfs(row, col - 1);
dfs(row + 1, col);
dfs(row - 1, col);
}