Leetcode 1396 Solution

This article provides solution to leetcode question 1396 (count-servers-that-communicate)

https://leetcode.com/problems/count-servers-that-communicate

Solution

class Solution:
    def countServers(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])

        row_srvs = [0] * m
        col_srvs = [0] * n

        for i in range(m):
            s = 0
            for j in range(n):
                s += grid[i][j]
            row_srvs[i] = s

        for j in range(n):
            s = 0
            for i in range(m):
                s += grid[i][j]
            col_srvs[j] = s

        ans = 0
        for i in range(m):
            for j in range(n):
                if grid[i][j] == 0:
                    continue

                if row_srvs[i] > 1 or col_srvs[j] > 1:
                    ans += 1
        return ans