Count Islands with DFS and BFS
Updated
Problem statement
You are given a rectangular binary grid in which 1 is land and 0 is water. An island is a maximal group of land cells connected horizontally or vertically.
Return the number of islands. Depth-first search and breadth-first search are alternative required solution strategies for the same result; the function returns one count.
Function
countIslands(grid: int[][]) → intExamples
Example 1
grid = [[1,1,0,0],[1,0,0,1],[0,0,1,1]]return = 2The upper-left land cells form one island, and the connected right-side cells form the other.
Example 2
grid = [[1,0,1],[0,1,0],[1,0,1]]return = 5Diagonal contact does not connect land, so every 1 is a separate island.
Example 3
grid = []return = 0An empty grid contains no land.
Constraints
0 <= rows, columns <= 500.- The grid is rectangular and contains at most
200000cells. - Every cell is either
0or1.
More Visa Online Assessment questions
- Count Prime Values in SubtreesOA · Seen Nov 2026
- Lock CodeOA · Seen Nov 2026
- Minimum-Sum Tree Fill with Unit StepsOA · Seen Nov 2026
- Longest Non-Decreasing Substring After Pair SwapsOA · Seen Oct 2026
- Count Attack Vectors by Divisor RangeOA · Seen Oct 2026
- Minimum Operations to Reduce a Transaction LedgerOA · Seen Oct 2026
- Count Valid Space-Delimited WordsOA · Seen Oct 2026
- Earliest Common Meeting StartOA · Seen Oct 2026
- Maximum Index-Weighted Sum with Disjoint SwapsOA · Seen Oct 2026
- Maximum Equalized Substrings After One Adjacent SwapOA · Seen Sep 2026
Similar questions at other companies
- Minimum Cleaning Robot RunsHSBC · OAHSBC interview questions
- Number of IslandsGoldman Sachs · OA · PHONE SCREEN · ONSITE INTERVIEWGoldman Sachs interview questions
- Maximum Damage PatchGecko Robotics · OA · PHONE SCREEN
- Count Connected Equal TilesIntuit · OAIntuit interview questions
- Number of IslandsAmazon · PHONE SCREEN · ONSITE INTERVIEW
- Number of Islands with Diagonal ConnectivityGoogle · ONSITE INTERVIEWGoogle interview questions
- Island Count and Maximum AreaOracle · ONSITE INTERVIEWOracle interview questions
- Count Connected IslandsUber · PHONE SCREENUber interview questions
- Number of IslandsSpaceX · PHONE SCREENSpaceX interview questions
- Mouse and Cheese ReachabilityMeta · ONSITE INTERVIEWMeta interview questions