Show problems as
Classic problem #1267MediumArrayDepth-First SearchBreadth-First SearchUnion-FindMatrixCounting

Count Servers that Communicate

Real-world version: Which Units Can Reach Another
Tracked in this browser only
Read Count Servers that Communicate on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

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 starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

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