chyam

[프로그래머스 Lv2, python] - [PCCP 기출문제] 2번 / 석유 시추 본문

프로그래머스/LV2

[프로그래머스 Lv2, python] - [PCCP 기출문제] 2번 / 석유 시추

chyam_eun 2025. 5. 5. 15:39

https://school.programmers.co.kr/learn/courses/30/lessons/250136

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

from collections import deque

def solution(land): # 마지막에 res의 max값 구하기
    r, c = len(land), len(land[0])
    visited = [[False]* c for i in range(r)]
    direction = [(0,1), (0,-1), (1,0) ,(-1,0)] # 상하좌우
    res = [0] * c
    
    def bfs(i, j): 
        queue = deque([(i, j)])
        visited[i][j] = True
        cnt = 1
        tmp = []
        while queue:
            x, y = queue.popleft()
            if y not in tmp: # 열 번호를 새로운 리스트에 저장
                tmp.append(y)
            for dx, dy in direction:
                nX, nY = x + dx, y + dy
                if 0 <= nX < r and 0 <= nY < c and not visited[nX][nY] and land[nX][nY] == 1:
                    cnt += 1 # 이웃하는 1의 개수 세기
                    visited[nX][nY] = True
                    queue.append([nX, nY])
        for i in tmp: # 이후에 이 열들에 1의 개수 더해주기
            res[i] += cnt    
        

    for i in range(r):
        for j in range(c):
            if land[i][j] == 1 and not visited[i][j]:
                bfs(i, j)
    return max(res)