How do I count the number of islands in a 2D grid using TypeScript?
To count islands in a 2D grid, you can use depth-first search (DFS) or breadth-first search (BFS) to explore each landmass, marking visited cells.
Counting the number of islands in a 2D grid is a common graph traversal problem where islands are defined as connected components of land (represented by 1s) surrounded by water (represented by 0s). The challenge is to identify all distinct islands by exploring each land cell and marking its connected land cells as visited. This can be done using either depth-first search (DFS) or breadth-first search (BFS). DFS explores the island by moving as deep as possible into neighboring land cells before backtracking, while BFS explores all neighbors level by level. Both approaches are valid and have a time complexity of O(n), where n is the number of cells in the grid. Understanding this algorithm is crucial for solving grid-based problems in TypeScript, as it has applications in geographical mapping, image processing, and network clustering.