Skip to content

Latest commit

 

History

History
51 lines (36 loc) · 1.49 KB

_1267. Count Servers that Communicate.md

File metadata and controls

51 lines (36 loc) · 1.49 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : January 23, 2025

Last updated : January 23, 2025


Related Topics : Array, Depth-First Search, Breadth-First Search, Union Find, Matrix, Counting

Acceptance Rate : 73.47 %


Solutions

Python

class Solution:
    def countServers(self, grid: List[List[int]]) -> int:
        rows, cols = defaultdict(set), defaultdict(set)

        for r, row in enumerate(grid) :
            for c, cell in enumerate(row) :
                if not cell :
                    continue

                rows[r].add(c)
                cols[c].add(r)

        output = sum([len(cnt) for r, cnt in rows.items() if len(cnt) > 1]) + \
                 sum([len(cnt) for c, cnt in cols.items() if len(cnt) > 1])

        for r, row in enumerate(grid) :
            for c, cell in enumerate(row) :
                if not cell :
                    continue
                if len(rows[r]) > 1 and len(cols[c]) > 1 :
                    output -= 1

        return output