All problems
1081MediumArrayDepth-First SearchBreadth-First SearchUnion-FindMatrixCounting

Which Units Can Reach Another

Tracked in this browser only
Write code

Trains the technique from

LeetCode 1267Count Servers that Communicate

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A rack is laid out as the grid grid, where 1 marks a cell holding a unit and 0 marks an empty cell.

Two units can reach each other when they share a row or share a column.

Return how many units can reach at least one other unit.

Examples

Example 1

Input
grid = [[1, 1, 1]]
Output
3

All three units share the single row, so each reaches the other two.

Example 2

Input
grid = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
Output
0

Each unit has its own row and its own column to itself, so none can reach another.

Example 3

Input
grid = [[0, 1, 0], [1, 0, 1], [0, 1, 0]]
Output
4

The two units in the middle row reach each other, and the units above and below share their column with the middle one, so all four count.

Constraints

  • 1 <= grid.length <= 250
  • 1 <= grid[i].length <= 250
  • 0 <= grid[i][j] <= 1

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def count_servers(grid: list[list[int]]) -> int:
Java
public int countServers(int[][] grid)
September 7
Apply