PPractick

DSA interview question

Number of Islands (8-Directional Connectivity)

Medium · Data structures · Topics: graph, dfs, bfs

The problem

A satellite image is a grid where '1' is land and '0' is water. For a coastline survey, two land cells belong to the same island if they touch horizontally, vertically or diagonally (8 directions). Count the islands. Each island is a connected component of land cells. Scan the grid, and every time you find land that hasn't been visited, count a new island and flood-fill it with BFS or DFS over all 8 neighbours, marking it visited.

Example: grid 0111000 / 0011010 → 2.

Function signature

int numIslands8(const vector<string>& grid);  // '1' land, '0' water; 8-directional

Test cases

Input (rows)OutputExplanation
01 / 10 / 11 / 101The diagonal joins the top 1 to the rest
0111000 / 00110102The single 1 at the far right is separate
101 / 010 / 1011All joined through the centre diagonally
100 / 0012Not adjacent, even diagonally
0000

(Confirm: adjacency includes the four diagonals; the grid may be non-square.)

How interviewers phrase it

Clarifying questions to ask

  1. 4 or 8 directions? (8 here.)
  2. May I modify the grid to mark visited cells? (If yes, no visited array is needed.)
  3. How large is the grid? (Up to 500 × 500, so recursion could get deep: prefer BFS.)

Follow-ups to expect

  1. "How do you enumerate 8 neighbours?"
  2. "Why BFS instead of recursive DFS?"
  3. "DSU alternative?"
  4. "What changes for 4 directions?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in