Click4Ai

321.

Medium

Connected Components

**Problem Statement:** Given a binary image, find the connected components (regions) in the image. A connected component is a region of pixels that are all connected to each other by a path of neighboring pixels.

Example:

Suppose we have a binary image represented as a 2D array:

image = np.array([[0, 0, 1, 1],

[0, 1, 1, 0],

[0, 0, 0, 0]])

The connected components in this image are two regions: one with pixels (1, 1), (2, 1), (3, 1), (1, 2), (2, 2), (3, 2) and another with pixels (3, 3), (4, 3).

**Constraints:** The input image is a 2D array of binary values (0 or 1).

**Solution:** Write a function to find the connected components in the given image.

Test Cases

Test Case 1
Input: [[0, 0, 1, 1], [0, 1, 1, 0], [0, 0, 0, 0]]
Expected: [[0, 0, 1, 1], [0, 1, 1, 0], [0, 0, 0, 0]]
Test Case 2
Input: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
Expected: [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
+ 3 hidden test cases