← Back to challenges

Number of Separate Regions

JavaScriptHardalgorithmsarraysconditionsloops

Instructions

The function is given a rectangular matrix consisting of zeros and ones. Count the number of different regions and return the result. A separate region is a collection of ones interconnected horizontally and vertically. A region can have holes in it.

Examples

numRegions([
  [1, 1, 1, 1, 0],
  [1, 1, 0, 1, 0],
  [1, 1, 0, 0, 0],
  [0, 0, 0, 0, 0]
]) ➞ 1

numRegions([
  [1, 1, 1, 1, 0],
  [1, 0, 0, 1, 0],
  [1, 1, 1, 1, 0],
  [0, 0, 0, 0, 1]
]) ➞ 2

// The region on the upper left looks like a doughnut.

numRegions([
  [1, 1, 0, 0, 0],
  [1, 1, 0, 0, 0],
  [0, 0, 1, 0, 1],
  [0, 0, 0, 1, 1]
]) ➞ 3

Notes

N/A

javascript
Loading editor…
to run
Walks through the solution with reasoning and edge cases.