Number of Islands with Diagonal Connectivity
Updated
Problem statement
Given a non-empty rectangular binary matrix grid, return the number of islands.
An island is a maximal group of cells containing 1. Two land cells belong to the same island when they touch horizontally, vertically, or diagonally. In other words, each cell has up to eight neighbors.
Cells containing 0 are water. You may modify grid.
Function
countIslands(grid: int[][]) → intExamples
Example 1
grid = [[1,0,0],[0,1,0],[0,0,1]]return = 1All three land cells connect through diagonals, so they form one island.
Example 2
grid = [[1,1,0,0],[0,1,0,1],[0,0,0,1]]return = 2The upper-left land group and the rightmost vertical pair do not touch in any of the eight directions.
Example 3
grid = [[0,0],[0,0]]return = 0The matrix contains no land cells.
Constraints
1 <= grid.length <= 500.1 <= grid[i].length <= 500.- Every row has the same length.
grid[i][j]is either0or1.- You may modify
grid.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Island Count and Maximum AreaOracle · ONSITE INTERVIEW
- Max Area of IslandGoldman Sachs · ONSITE INTERVIEW
- Max Area of IslandRoku · ONSITE INTERVIEW
- Max Area of IslandBloomberg LP · ONSITE INTERVIEW
- Maximum Area of IslandSambaNova Systems · ONSITE INTERVIEW
- Count Islands in a Binary GridApple · PHONE SCREEN
- Pacific Atlantic Water FlowAnduril · PHONE SCREEN
- Maximum Damage PatchGecko Robotics · OA · PHONE SCREEN
- Maximum Area of IslandSkydio · PHONE SCREEN
- Number of IslandsFleetx · ONSITE INTERVIEW