codejump
MediumPythonJavaScriptTypeScript

Graph DFS — Number of Islands

Data StructuresGraphDFSMatrix

A grid is a graph you never have to build: each cell is a node and its
neighbours are the four cells above, below, left and right.

grid is a matrix of 1 (land) and 0 (water). Count the islands —
groups of land cells connected horizontally or vertically. Diagonals do not
connect.

Examples

solve([
  [1, 1, 0, 0],
  [1, 0, 0, 1],
  [0, 0, 1, 1],
])  → 2

solve([[1, 0, 1], [0, 1, 0], [1, 0, 1]])  → 5   // diagonals do not connect
solve([[0, 0], [0, 0]])                   → 0

Constraints

  • The grid can be empty.
  • Avoid recursion depth problems on a big grid by using an explicit stack or

queue if you prefer.

  • Do not count a land cell twice: mark it visited (sinking it to 0 on a copy

of the grid is the usual trick).

Sample tests

Test #1Two islands of different shapes
Input: [[[1,1,0,0],[1,0,0,1],[0,0,1,1]]]
Output: 2
Test #2Diagonals do not connect — five one-cell islands
Input: [[[1,0,1],[0,1,0],[1,0,1]]]
Output: 5
Test #3All water
Input: [[[0,0],[0,0]]]
Output: 0