강의로 돌아가기
박동현

효율성 실패하시는 분들

갈림길에서 여러명을 복제해서 각각 길을 찾는 연산을 한다고 생각하지 마시고

갈림길에서 액체가 퍼지듯 동시에 길을 찾게 해야 성공합니다.

작성중인 코드―solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from collections import deque


def next_step(maps, p):
    nexts = deque()
    n = len(maps) # row size
    m = len(maps[0]) # col size

    # (down, right, up, left)
    for t in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        if 0 <= p[0] + t[0] < n and 0 <= p[1] + t[1] < m:
            if maps[p[0]+t[0]][p[1]+t[1]] == 1:
                nexts.append((p[0]+t[0], p[1]+t[1]))

    return nexts


def solution(maps):
    answer = -1
    n = len(maps)
    m = len(maps[0])

    end = (n-1, m-1)
    begin = (0, 0)
    maps[0][0] = 0
    begin_item = [begin, 1] # [point, cnt]

    q = deque([begin_item])
    while q:
        current, cnt = q.popleft()

        if current == end:
            return cnt

        nxts = next_step(maps, current)
        for nxt in nxts:
            q.append([nxt, cnt+1])
            maps[nxt[0]][nxt[1]] = 0

    return answer
  • wndlsrnr3@gmail.com

    ㄷㄷ 균사체형 최단경로 길찾기

    wndlsrnr3@gmail.com―2023.01.07 14:25
0 개의 답변
답변 쓰기
이 입력폼은 마크다운 문법을 지원합니다. 마크다운 가이드 를 참고하세요.