Leetcode #1267: Count Servers that Communicate
In this guide, we solve Leetcode #1267 Count Servers that Communicate in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Depth-First Search, Breadth-First Search, Union Find, Array, Counting, Matrix
Intuition
We need to explore a structure deeply before backing up, which suits DFS.
DFS keeps local context on the call stack and is easy to implement recursively.
Approach
Define a recursive DFS that carries the necessary state.
Combine child results as the recursion unwinds.
Steps:
- Define a recursive DFS with state.
- Visit children and combine results.
- Return the final aggregation.
Example
Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.
Python Solution
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
row = [0] * m
col = [0] * n
for i in range(m):
for j in range(n):
row[i] += grid[i][j]
col[j] += grid[i][j]
return sum(
grid[i][j] and (row[i] > 1 or col[j] > 1)
for i in range(m)
for j in range(n)
)
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.