1267. Count Servers that Communicate
Difficulty: Medium
Topics: Array, Depth-First Search, Breadth-First Search, Union Find, Matrix, Counting
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.
Example 1:
Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.
Example 3:
<?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function countServers($grid) {
...
...
...
/**
* go to ./solution.php
*/
}
// Test the function with the provided examples
$grid1 = [[1, 0], [0, 1]];
$grid2 = [[1, 0], [1, 1]];
$grid3 = [[1, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1]];
echo countServers($grid1) . "\n"; // Output: 0
echo countServers($grid2) . "\n"; // Output: 3
echo countServers($grid3) . "\n"; // Output: 4
?>
Explanation:
Counting Servers in Rows and Columns:
- We iterate over the grid and count how many servers (i.e.,
1s) are in each row and each column. We store these counts in therowCountandcolCountarrays.
- We iterate over the grid and count how many servers (i.e.,
Identifying Communicating Servers:
- After counting, we iterate over each server (cell with value
1). A server can communicate with others if the count of servers in its row (rowCount[i] > 1) or the count of servers in its column (colCount[j] > 1) is greater than 1. We then increment the result counter for each communicating server.
- After counting, we iterate over each server (cell with value
Output:
- The function returns the total count of servers that can communicate with other servers.
Time Complexity:
O(m * n), wheremis the number of rows andnis the number of columns. This is because we iterate through the grid twice: once to count servers in rows and columns, and once to check for communication.
This solution efficiently handles the problem within the given constraints.
Contact Links
If you found this series helpful, please consider giving the
If you want more helpful content like this, feel free to follow me:
SOCIAL SHARE CARD GENERATOR