찾다
백엔드 개발파이썬 튜토리얼깊이 우선 탐색의 언덕을 오르다, Advent of Code day 10

오늘의 챌린지는 6일차와 비슷하지만 여러 경로를 탐색해야 하는 2D 그리드인 10일차 퍼즐을 다룹니다. 이 퍼즐은 깊이 우선 검색(DFS)의 힘을 우아하게 보여줍니다.

Climbing a depth-first search hill, Advent of Code day 10
AI가 만든 퍼즐 일러스트

지도는 사전으로 표현됩니다. 키는 (x, y) 좌표이고 값은 높이를 나타내는 한 자리 정수(0-9)이며, 9는 최고점을 나타냅니다. 구문 분석 기능은 다음 데이터 구조를 효율적으로 처리합니다.

def parse(input: str) -> dict[tuple[int, int], int | None]:
    return {
        (x, y): int(item) if item.isdigit() else None
        for y, row in enumerate(input.strip().splitlines())
        for x, item in enumerate(row)
    }

트레일은 트레일 시작점(높이 0)에서 정상(높이 9)까지 올라가며 높이가 단계당 정확히 1씩 증가합니다. next_step 함수는 유효한 다음 단계를 식별합니다.

TRAIL_MAX = 9

def next_step(
    topo_map: dict[tuple[int, int], int | None], x: int, y: int
) -> tuple[tuple[int, int], ...]:
    assert topo_map[(x, y)] != TRAIL_MAX

    return tuple(
        incoming
        for incoming in (
            (x + 1, y),
            (x, y + 1),
            (x - 1, y),
            (x, y - 1),
        )
        if (
            isinstance(topo_map.get(incoming), int)
            and isinstance(topo_map.get((x, y)), int)
            and (topo_map[incoming] - topo_map[(x, y)] == 1)
        )
    )

트레일헤드(높이 0)는 find_trailheads:

을 사용하여 위치를 지정합니다.
TRAILHEAD = 0

def find_trailheads(
    topo_map: dict[tuple[int, int], int | None],
) -> tuple[tuple[int, int], ...]:
    return tuple(key for key, value in topo_map.items() if value == TRAILHEAD)

솔루션의 핵심은 깊이우선탐색을 구현한 climb 기능입니다. Wikipedia의 DFS 정의에 따라 역추적하기 전에 각 분기를 완전히 탐색합니다.

Climbing a depth-first search hill, Advent of Code day 10
깊이우선탐색의 시각적 표현

지도 지점은 "노드"이며 한 번에 한 높이씩 올라갑니다. climb 함수는 DFS 프로세스를 관리합니다.

def climb(
    topo_map: dict[tuple[int, int], int | None], trailheads: tuple[tuple[int, int], ...]
) -> dict[
    tuple[tuple[int, int], tuple[int, int]], tuple[tuple[tuple[int, int], ...], ...]
]:
    candidates: list[tuple[tuple[int, int], ...]] = [(head,) for head in trailheads]

    result = {}

    while candidates:
        current = candidates.pop()
        while True:
            if topo_map[current[-1]] == TRAIL_MAX:
                result[(current[0], current[-1])] = result.get(
                    (current[0], current[-1]), ()
                ) + (current,)
                break

            elif steps := next_step(topo_map, *current[-1]):
                incoming, *rest = steps

                candidates.extend([current + (step,) for step in rest])

                current = current + (incoming,)
            else:
                break

    return result

else 절의 break은 막다른 골목을 처리하여 무한 루프를 방지합니다. 이 함수는 각 트레일 기점에서 정상까지의 모든 경로를 반환합니다.

1부에서는 고유한 최고 목적지를 계산합니다.

def part1(input: str) -> int:
    topo_map = parse(input)

    return len(climb(topo_map, find_trailheads(topo_map)))

2부에서는 모든 고유 경로를 계산합니다.

def part2(input: str) -> int:
    topo_map = parse(input)

    return sum(
        len(routes) for routes in climb(topo_map, find_trailheads(topo_map)).values()
    )

대체 접근 방식(예: 트레일 시작 부분 감지를 구문 분석에 통합)이 존재하지만 이 솔루션의 성능은 괜찮습니다. 최근 구직 활동의 실패로 인해 내 기분이 꺾이지는 않았습니다. 나는 여전히 희망적이다. 중급 Python 개발자를 찾고 있다면 연락하세요. 다음주까지!

위 내용은 깊이 우선 탐색의 언덕을 오르다, Advent of Code day 10의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?목록과 배열 사이의 선택은 큰 데이터 세트를 다루는 파이썬 응용 프로그램의 전반적인 성능에 어떤 영향을 미칩니 까?May 03, 2025 am 12:11 AM

forhandlinglargedatasetsinpython, usenumpyarraysforbetterperformance.1) numpyarraysarememory-effic andfasterfornumericaloperations.2) leveragevectorization foredtimecomplexity.4) managemoryusage withorfications data

Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.Python의 목록 대 배열에 대한 메모리가 어떻게 할당되는지 설명하십시오.May 03, 2025 am 12:10 AM

inpython, listsusedyammoryAllocation과 함께 할당하고, whilempyarraysallocatefixedMemory.1) listsAllocatemememorythanneedInitiality.

파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?파이썬 어레이에서 요소의 데이터 유형을 어떻게 지정합니까?May 03, 2025 am 12:06 AM

Inpython, youcansspecthedatatypeyfelemeremodelerernspant.1) usenpynernrump.1) usenpynerp.dloatp.ploatm64, 포모 선례 전분자.

Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?Numpy 란 무엇이며 Python의 수치 컴퓨팅에 중요한 이유는 무엇입니까?May 03, 2025 am 12:03 AM

numpyissentialfornumericalcomputinginpythonduetoitsspeed, memory-efficiency 및 comperniveMathematicaticaltions

'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.'연속 메모리 할당'의 개념과 배열의 중요성에 대해 토론하십시오.May 03, 2025 am 12:01 AM

contiguousUousUousUlorAllocationScrucialForraysbecauseItAllowsOfficationAndFastElementAccess.1) ItenableSconstantTimeAccess, o (1), DuetodirectAddressCalculation.2) Itimprovesceeffiency theMultipleementFetchespercacheline.3) Itsimplififiesmomorym

파이썬 목록을 어떻게 슬라이스합니까?파이썬 목록을 어떻게 슬라이스합니까?May 02, 2025 am 12:14 AM

slicepaythonlistisdoneusingthesyntaxlist [start : step : step] .here'showitworks : 1) startistheindexofthefirstelementtoinclude.2) stopistheindexofthefirstelemement.3) stepisincrementbetwetweentractionsoftortionsoflists

Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?Numpy Array에서 수행 할 수있는 일반적인 작업은 무엇입니까?May 02, 2025 am 12:09 AM

NumpyAllowsForVariousOperationsOnArrays : 1) BasicArithmeticLikeadDition, Subtraction, A 및 Division; 2) AdvancedOperationsSuchasmatrixmultiplication; 3) extrayintondsfordatamanipulation; 5) Ag

파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?파이썬으로 데이터 분석에 어레이가 어떻게 사용됩니까?May 02, 2025 am 12:09 AM

Arraysinpython, 특히 Stroughnumpyandpandas, areestentialfordataanalysis, setingspeedandefficiency

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.