MemotivaLeetCode Patterns Flashcards: Graphs, BFS, DFS, Topological Sort, Union Find

How does the number of islands problem use graph traversal?

LeetCode Patterns Flashcards: Graphs, BFS, DFS, Topological Sort, Union Find

Аудио-карточка · 0:27

Nortren·

How does the number of islands problem use graph traversal?

0:27

Treat the grid as a graph where each land cell connects to its adjacent land cells. Iterate through every cell. When an unvisited land cell is found, increment the island count and run DFS or BFS from that cell, marking all connected land cells as visited. This explores the entire island in one traversal. After the traversal, all cells belonging to that island are marked, so they will not be counted again. The total island count equals the number of times you initiate a new traversal. This runs in O of rows times columns time.
neetcode.io