Data Structures & AlgorithmsVery hardProduct company OA

In this grid, how many islands of 1s are there with 4-directional connectivity, and how many with 8-directional (diagonals also connect)?

In this grid, how many islands of 1s are there with 4-directional connectivity, and how many with 8-directional (diagonals also connect)?
1 0 0 1 1
0 1 0 0 1
0 0 1 0 0
1 0 0 0 1
1 1 0 1 0
  1. A. 7 and 3
  2. B. 6 and 4
  3. C. 8 and 4
  4. D. 7 and 4

Correct answer: D. 7 and 4

4-connected: {(0,0)}, {(1,1)}, {(2,2)}, {(0,3),(0,4),(1,4)}, {(3,0),(4,0),(4,1)}, {(3,4)}, {(4,3)} = 7. With diagonals, (0,0)-(1,1)-(2,2) join into one island and (3,4)-(4,3) join into another; the top-right group and the bottom-left group touch nothing diagonally, so they stay separate: 4. Merging (2,2) with a neighbouring group (it has none diagonally) gives 3.

More Trees, Graphs, Recursion and Dynamic Programming questions

Exams that ask this topic