An interactive visualization of DFS flood fill on a 2D grid. Watch how depth-first search discovers and marks each connected island, one cell at a time.
DFS LeetCode 200 โ Mediumm x n 2D binary grid grid which represents a map of
'1's (land) and '0's (water), return the number of islands.fun numIslands(grid: Array<CharArray>): Int { if (grid.isEmpty()) return 0 val rows = grid.size val cols = grid[0].size var count = 0 fun dfs(r: Int, c: Int) { if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] != '1') return grid[r][c] = '#' // mark visited dfs(r + 1, c) dfs(r - 1, c) dfs(r, c + 1) dfs(r, c - 1) } for (r in 0 until rows) { for (c in 0 until cols) { if (grid[r][c] == '1') { count++ dfs(r, c) } } } return count }
Every unvisited land cell ('1') is either part of an already-counted island or the start of a brand-new one.
When we find an unvisited '1', we increment the island count and use DFS to "flood fill" the entire connected component,
marking every reachable land cell as visited so it won't be counted again.
'1' (unvisited land), increment count and launch a DFS from that cell.'#'), then recursively visit all four neighbors (up, down, left, right).'0'), or already visited ('#'), return immediately.count holds the total number of islands.Every cell is visited at most once during scanning and at most once during DFS, giving O(m ร n) time. The space complexity is O(m ร n) in the worst case for the recursion stack โ imagine a grid filled entirely with land, where DFS would recurse through all m ร n cells.