LeetCode 1267. Count Servers that Communicate解题报告(python)
程序员文章站
2022-03-05 12:58:41
...
1267. Count Servers that Communicate
- Count Servers that Communicatepython solution
题目描述
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.
解析
遍历统计,按行和按列。只要有同行或同列满足count_X>1即可。
class Solution:
def countServers(self, grid: List[List[int]]) -> int:
count=0
row=len(grid)
col=len(grid[0])
count_row=row*[0]
count_col=col*[0]
for i in range(row):
for j in range(col):
if grid[i][j]==1:
count_row[i]+=1
count_col[j]+=1
for i in range(row):
for j in range(col):
if grid[i][j]==1 and (count_row[i]>1 or count_col[j]>1):
count+=1
return count