Count Servers that Communicate
Real-world version: Which Units Can Reach AnotherThe 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.
def count_servers(grid: list[list[int]]) -> int:public int countServers(int[][] grid)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's