Count the Rail Regions

Easy · Union-Find · about 15 min

There are n towns. The table linked is n × n: linked[i][j] is 1 when a direct train line runs between towns i and j, and 0 otherwise. The table is symmetric and linked[i][i] is 1.

A region is a group of towns where every town can reach every other by train, possibly changing lines on the way. Return the number of regions. An empty table gives 0.

Example:

count_rail_regions([[1, 1, 0], [1, 1, 0], [0, 0, 1]]) → 2

Hints

  • Give every town a parent, starting with itself. Write a find that follows parents up to the leader.
  • Look at each pair i < j with a line. Join their leaders, and only lower the region count when the leaders were different.

Learn the pattern first: the Union-Find lesson.

More Union-Find problems