[프로그래머스] [PCCP 기출문제] 2번

yewon Lee·2023년 11월 27일
0


😎코딩테스트 연습>PCCP 기출문제>[PCCP 기출문제] 2번


📘 문제풀이

from collections import deque

def solution(land):
    answer = 0
    
    n = len(land) #세로길이
    m = len(land[0]) #가로길이
    
    d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
    
    visited = [[False] * m for _ in range(n)]
    q = deque()
    
    num = 0 #석유구역 번호
    arr = [0] #석유 구역마다 석유량    
    
    for i in range(n):
        for j in range(m):
            if visited[i][j] == False and land[i][j] == 1:                
                arr.append([0])
                num += 1
                cnt = 1 #석유량
                visited[i][j] = True
                q.append((i,j))
                land[i][j] = num

                while q:
                    px, py = q.popleft()
                    
                    for k in range(4):
                        nx = px + d[k][0]
                        ny = py + d[k][1]
                        
                        if 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == False and land[nx][ny] == 1:
                            q.append((nx, ny))
                            visited[nx][ny] = True
                            land[nx][ny] = num
                            cnt += 1
                arr[num] = cnt            
    
    for i in range(m):
        #열마다 어떤 석유 구역이 있는지 체크
        s = []
        c = 0
        for j in range(n):
            if land[j][i] != 0 and land[j][i] not in s:
                s.append(land[j][i])
        
        #석유 최대량 찾기
        for k in s: 
            c += arr[k]

        if c > answer:
            answer = c
            
    return answer
profile
시작

0개의 댓글