1267. Count Servers that Communicate #1214
-
Topics: You are given a map of a server center, represented as a Return the number of servers that communicate with any other server. Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We'll follow these steps: Approach:
Let's implement this solution in PHP: 1267. Count Servers that Communicate <?php
/**
* @param Integer[][] $grid
* @return Integer
*/
function countServers($grid) {
$m = count($grid); // Number of rows
$n = count($grid[0]); // Number of columns
$rowCount = array_fill(0, $m, 0); // Array to store server counts in each row
$colCount = array_fill(0, $n, 0); // Array to store server counts in each column
// Step 1: Count the number of servers in each row and column
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($grid[$i][$j] == 1) {
$rowCount[$i]++;
$colCount[$j]++;
}
}
}
// Step 2: Count the number of servers that communicate
$result = 0;
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
if ($grid[$i][$j] == 1) {
// A server communicates if its row or column has more than 1 server
if ($rowCount[$i] > 1 || $colCount[$j] > 1) {
$result++;
}
}
}
}
return $result;
}
// 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:
Time Complexity:
This solution efficiently handles the problem within the given constraints. |
Beta Was this translation helpful? Give feedback.
We'll follow these steps:
Approach:
Count Servers in Each Row and Column:
rowCount
andcolCount
, where:rowCount[i]
stores the number of servers in rowi
.colCount[j]
stores the number of servers in columnj
.Check for Communication:
rowCount
andcolCount
. If either is greater than 1, then the server can communicate with others.Count the Servers that Communicate:
1
), check if it belongs to a row o…