코딩 공부/Leetcode

[Python] 1267. Count Servers that Communicate

일하는 공학도 2025. 1. 23. 11:28
728x90

난이도 : Medium

 

서로 동일한 행이나 동일한 열에 두 서버가 있으면, 서버가 작동하는 것으로, 작동하는 서버의 갯수를 세는 문제

 

그냥 행렬 중 한 쪽에서 2개 이상 있으면 되는 문제..!

 

class Solution:
    def countServers(self, grid: List[List[int]]) -> int:
        m = len(grid)
        n = len(grid[0])
        r = [sum(row) for row in grid]
        c = [sum(grid[i][j] for i in range(m)) for j in range(n)]
        count = 0

        for i in range(m):
            for j in range(n):
                if grid[i][j] == 1 and (r[i] > 1 or c[j] > 1):
                    count += 1
        
        return count
  1. 행과 열의 수를 m, n으로 지정
  2. r은 행 기준으로 서버가 총 몇개가 있는가, c는 열 기준으로 서버가 총 몇개가 있는가 세기
  3. grid의 특정 요소가 1이고, 특정 요소의 위치에 있는 행과 열에 두 개 이상의 서버가 있는지 확인

Runtime : 30ms (20.97%)

Memory : 19.97MB (14.98%)

728x90

'코딩 공부 > Leetcode' 카테고리의 다른 글

[Python] 2429. Minimize XOR  (0) 2025.01.24
[Python] 802. Find Eventual Safe States  (0) 2025.01.24
[Python] 26. Remove Duplicates from Sorted Array  (0) 2025.01.20
[Python] 383. Ransom Note  (0) 2025.01.19
[Python] 27. Remove Element  (0) 2025.01.18