FastPrepCount Islands with Eight-Direction Adjacency
Problems/Count Islands with Eight-Direction Adjacency

Count Islands with Eight-Direction Adjacency

Amazon logoAmazon● MediumFULLTIMEPHONE SCREEN
QuestionFunctionExamplesConstraints

Problem statement

Source note: The source directly asks to count islands with horizontal, vertical, and diagonal adjacency and reports that a supplied 5×5 grid has answer 4, although the frozen evidence does not retain that grid's cells. The judged task preserves the stated eight-direction rule and matches the available source at about 96%.

Given a 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 share an edge or a corner, so each cell can connect in any of the eight horizontal, vertical, or diagonal directions.

Function

countIslands8(grid: int[][]) → int

Examples

Example 1

grid = [[1,0,1],[0,1,0],[1,0,1]]return = 1

Every land cell connects to the center diagonally, so all five cells form one island.

Example 2

grid = [[1,1,0],[0,0,0],[0,1,1]]return = 2

The upper-left and lower-right land groups do not touch, even at a corner.

Example 3

grid = [[0,0],[0,0]]return = 0

There are no land cells.

Constraints

  • 1 <= grid.length, grid[i].length <= 500.
  • Every row has the same length.
  • grid[i][j] is either 0 or 1.
  • The matrix contains at most 100000 cells.

More Amazon problems

  • Count Adjacent Symbol Pairs for BPEONSITE INTERVIEW · Seen Nov 2026
  • First Non-Repeating CharacterOA · ONSITE INTERVIEW · Seen Nov 2026
  • Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
See Amazon hiring insights
Saved
class Solution {
    public int countIslands8(int[][] grid) {
      // write your code here
    }
}
Checking account…