Microsoft | Phone Screen | Find total number of regions

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2022-05-15Added By Anonymous
Source: Link

Find the total number of regions in a two dimensional array.

0 represents water and hence its not considered as region and any other decimal number 1 to n represents a region. Up, down, left, right neighbors cordinates are considered for calculating regions.

Ex:

[ [2, 0],

[2, 2] ]

There is only one region formed by 2s

Example 2:

[[3, 1, 0],

[2, 3, 0],

[2, 2, 0]]

Here there are 4 regions formed by 1s, 2s, region formed by 3s considered as two different regions as they are diagnol to each other

Example 3:

[[1, 1, 0, 0,3],

[1, 0, 2, 0,0],

[2, 2, 2, 0,0],

[5, 5, 2, 0,4],

[0, 0, 3, 3, 0]]

Six regions formed by 1s, 2s, 3s (twice), 4s and 5s

Comments