Count Islands with Eight-Direction Adjacency
Problem statement
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[][]) → intExamples
Example 1
grid = [[1,0,1],[0,1,0],[1,0,1]]return = 1Every 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 = 2The upper-left and lower-right land groups do not touch, even at a corner.
Example 3
grid = [[0,0],[0,0]]return = 0There are no land cells.
Constraints
1 <= grid.length, grid[i].length <= 500.- Every row has the same length.
grid[i][j]is either0or1.- The matrix contains at most
100000cells.