V

Algorithm Visualizer

ZHEN
Share on WeiboShare on XGitHub repositoryAuthor website
Learning ToolsAlgorithm Complexity ReferenceAlgorithm Learning Paths
Data StructuresArrayLinked ListStackQueue and DequeBinary Search TreeBinary HeapHash TableGraphTrieDisjoint Set UnionLRU CacheSkip ListSegment TreeB+ TreeBloom FilterFenwick Tree
SortingBubble SortCocktail Shaker SortBitonic SortSelection SortInsertion SortBinary Insertion SortShell SortMerge SortTop-Down Merge SortQuick SortThree-Way Quick SortDual-Pivot Quick SortHeap SortCounting SortRadix SortBucket Sort
Graph AlgorithmsDijkstra's Shortest PathKruskal's Minimum Spanning TreePrim's Minimum Spanning TreeBellman-Ford Shortest PathsTopological SortFloyd-WarshallStrongly Connected Components2-SATMaximum FlowBipartite MatchingLowest Common AncestorEulerian Path
Dynamic ProgrammingEdit Distance0/1 KnapsackUnbounded KnapsackLongest Common SubsequenceLongest Increasing SubsequenceCoin ChangeStone MergingTraveling Salesperson DPTree Dynamic ProgrammingDigit DPRerooting DP
Backtracking and SearchN-QueensSubsetsPermutationsCombination SumMaze Solving with DFSNumber of IslandsWord SearchSudoku SolverA* Search
StringsKMP String MatchingRabin-Karp String MatchingBoyer-Moore String MatchingManacher's Longest Palindromic SubstringSuffix ArrayLCP ArrayAho-Corasick AutomatonZ Function
Math and Number TheorySieve of EratosthenesLinear SieveEuclidean AlgorithmBinary ExponentiationExtended Euclidean AlgorithmChinese Remainder TheoremEuler's Totient FunctionMiller-Rabin Primality TestFast Fourier TransformPollard's Rho Factorization
Computational GeometryConvex HullRotating CalipersClosest Pair of PointsLine Segment IntersectionBentley-Ottmann Sweep Line
SearchingBinary SearchLower and Upper BoundSearch in a Rotated Sorted ArrayBinary Search on the AnswerTernary Search

Number of Islands

Flood-fill each unseen land component and count how many independent searches begin.

Core idea

Scan the grid. Every unseen land cell starts one new component search, and that flood fill marks all land reachable through four-directional neighbors.

Read the visualization

The scan cursor moves row by row. A newly discovered island changes the traversal color, and the active frontier spreads until water or visited cells block it.

🔎

This unseen land cell starts a new island and a new flood fill.

1function numIslands(grid: number[][]): number {
2 const rows = grid.length, cols = grid[0].length;
3 let count = 0;
4 const flood = (r: number, c: number): void => {
5 if (r < 0 || r >= rows || c < 0 || c >= cols) return;
6 if (grid[r][c] === 0) return; // water / already visit
7 grid[r][c] = 0; // flood as already visit (flood)
8 flood(r - 1, c); flood(r + 1, c);
9 flood(r, c - 1); flood(r, c + 1);
10 };
11 for (let r = 0; r < rows; r++) {
12 for (let c = 0; c < cols; c++) {
13 if (grid[r][c] === 1) { // hit scan land
14 count++;
15 flood(r, c);
16 }
17 }
18 }
19 return count;
20}
grid4×4(1= land /0= water)
current cell(0,0)
island count1
counted land1
1 / 20

Complexity and tradeoffs

Time: O(RC). Space: O(RC). Every grid cell is visited at most once; iterative traversal can replace recursion.

Invariant: After a flood fill ends, every cell in that island is marked, so no later scan position can count it again.

Where it fits

Grid component labeling supports maps, image regions, board games, and cluster counting. Diagonal connectivity or weighted movement changes only the neighbor relation.