[programmers] PCCP 기출문제 2번 / 석유 시추 (python)

2024. 7. 3. 15:16·Study/algorithm
728x90
반응형

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr


정확성과 효율성 두 가지를 따지는 문제

bfs를 한번 돌려서 연결된 석유들을 모두 찾고 저장해둬서 다음번에는 다시 탐색 하지 않도록 하는것이 중요했다.


from collections import deque

def solution(land):
    answer = 0
    n, m = len(land), len(land[0])
    
    dx = [-1, 1, 0, 0]
    dy = [0, 0, -1, 1]
    
    # 각 열의 기름 총량
    result = [0 for i in range(m)]
    # 방문 기록
    visited = [[0 for _ in range(m)] for _ in range(n)]
    
    def bfs(pos):
        a, b = pos
        cnt = 1
        visited[a][b] = 1

        q = deque()
        q.append(pos)
        
        # 석유가 존재하는 열 저장 (중복 방지)
        oil_covered = set()
        oil_covered.add(b)
        
        while q:
            x, y = q.popleft()
            for i in range(4):
                nx, ny = x + dx[i], y + dy[i]
                if (0 <= nx < n) and (0 <= ny < m) and visited[nx][ny] == 0 and land[nx][ny] == 1:
                    q.append((nx, ny))
                    visited[nx][ny] = 1
                    cnt += 1
                    oil_covered.add(ny)
                    
        for c in oil_covered:
            result[c] += cnt
            
    for i in range(n):
        for j in range(m):
            if (land[i][j] == 1) and not visited[i][j]:
                bfs((i, j))
    
    answer = max(result)
    
    return answer
728x90
반응형

'Study > algorithm' 카테고리의 다른 글

[programmers] 요격 시스템 (python)  (0) 2024.07.03
[programmers] PCCP 기출문제 3번 / 아날로그 시계 (python)  (0) 2024.07.03
[softeer] [인증평가(4차) 기출] 슈퍼컴퓨터 클러스터 (python)  (1) 2022.09.29
[softeer] [21년 재직자 대회 본선] 트럭 (python)  (0) 2022.09.14
[softeer] [21년 재직자 대회 예선] 회의실 예약 (python)  (0) 2022.09.12
'Study/algorithm' 카테고리의 다른 글
  • [programmers] 요격 시스템 (python)
  • [programmers] PCCP 기출문제 3번 / 아날로그 시계 (python)
  • [softeer] [인증평가(4차) 기출] 슈퍼컴퓨터 클러스터 (python)
  • [softeer] [21년 재직자 대회 본선] 트럭 (python)
성장형감자
성장형감자
공부 기록
    반응형
  • 성장형감자
    단순하게
    성장형감자
  • 전체
    오늘
    어제
    • Category (66)
      • Paper review (38)
        • 2D Object detection (11)
        • 3D Object detection (20)
        • 2D Segmentation (1)
        • 2D Classification (5)
        • 3D classification (1)
      • Programming (4)
        • Python (1)
        • Linux (3)
      • Project (0)
      • Study (24)
        • algorithm (20)
        • etc. (1)
        • Radar (3)
  • 인기 글

  • 블로그 메뉴

    • 홈
  • 250x250
  • hELLO· Designed By정상우.v4.10.0
성장형감자
[programmers] PCCP 기출문제 2번 / 석유 시추 (python)
상단으로

티스토리툴바