As reported: Amazon SDE 2 (L5) phone screen (Bangalore, May 2025), second coding question: count the islands in an
m × ngrid of 0s and 1s where 1-cells are connected horizontally, vertically or diagonally.
You are given an m × n grid of 0s (water) and 1s (land). Two land cells belong to the same island if they touch in any of the 8 directions (including diagonals). Return the number of islands.
Example 1
grid = [[1,1,0,0,0],
[0,1,0,0,1],
[1,0,0,1,1],
[0,0,0,0,0],
[1,0,1,1,0]]
Output: 4
Example 2
grid = [[1,0,1],
[0,1,0],
[1,0,1]]
Output: 1 every corner touches the centre diagonally
Constraints: 1 ≤ m, n ≤ 300; grid[i][j] is 0 or 1.
Code runner format: one line: grid as a JSON array of arrays. Implement countIslands(grid); the harness prints the result.