Skip to content
DeepForgeby svx
All problems
HardComputer Visioncv-038

Count Connected Components

Problem

Count the connected components of 1-valued pixels in a binary mask using 4-connectivity.

Pixels that touch only diagonally belong to different components. An empty mask has 0 components.

Hint

Scan every pixel; when you hit an unseen 1, flood fill it and increment the count.

Test cases

case 1
in: [[[1,1,0],[0,1,0],[0,0,1]]]
expected: 2
case 2
in: [[[1,0],[0,1]]]
expected: 2
case 3
in: [[[0,0],[0,0]]]
expected: 0
case 4
in: [[[1,1,1],[1,1,1]]]
expected: 1
case 5
in: [[]]
expected: 0
Starter codePython
def count_components(mask):
    # Your code here
    pass

5 test cases · run your code against them in the editor