Skip to main content
Back to problems
#1267
Medium Algorithms

Count servers that communicate

Array Depth-First Search Breadth-First Search Union-Find Matrix Counting
73.5% acceptance
Feb 25, 2026
1910
108
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. Return the number of servers that communicate with any other server.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn count_servers(grid: Vec<Vec<i32>>) -> i32 {
    let m = grid.len();
    let n = grid[0].len();
    let row_count: Vec<i32> = grid.iter().map(|r| r.iter().sum()).collect();
    let col_count: Vec<i32> = (0..n).map(|c| (0..m).map(|r| grid[r][c]).sum()).collect();

    let mut ans = 0;
    for i in 0..m {
      for j in 0..n {
        if grid[i][j] == 1 && (row_count[i] > 1 || col_count[j] > 1) {
          ans += 1;
        }
      }
    }
    ans
  }
}