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 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.
For example:
Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.
Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.
Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.
Consider edge cases such as an empty grid, a grid with no servers, or a grid where all servers are isolated.
A brute force solution would involve iterating through each cell in the grid. For each cell containing a server (value of 1), we check if there is another server in the same row or column. If there is, we increment a counter. This approach is straightforward but not the most efficient.
def count_servers_brute_force(grid):
count = 0
rows = len(grid)
cols = len(grid[0])
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
communicating = False
# Check row
for k in range(cols):
if k != j and grid[i][k] == 1:
communicating = True
break
# Check column
if not communicating:
for k in range(rows):
if k != i and grid[k][j] == 1:
communicating = True
break
if communicating:
count += 1
return count
A more efficient solution involves pre-calculating the number of servers in each row and each column. Then, we iterate through the grid again. If a cell contains a server, we check if its row count or its column count is greater than 1. If it is, it means that the server can communicate with at least one other server. This approach avoids redundant checks.
def count_servers_optimal(grid):
rows = len(grid)
cols = len(grid[0])
row_counts = [0] * rows
col_counts = [0] * cols
# Calculate row and column counts
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1:
row_counts[i] += 1
col_counts[j] += 1
count = 0
for i in range(rows):
for j in range(cols):
if grid[i][j] == 1 and (row_counts[i] > 1 or col_counts[j] > 1):
count += 1
return count
row_counts
and col_counts
arrays.