Programming/Python2013. 6. 14. 00:46

A* 알고리즘을 구현해 보았다. 전체 코드는 Github 에 업로드 되어있다.

def calc_path(self):
        start = self.grid.start
        start.mindistance = 0.0
        start.h_value = self.heuristic(start)
        openset = [start]
        closedset = set()

        while openset:
            u = heapq.heappop(openset)
            closedset.add(u)

            if u == self.grid.goal:
                break

            for target in self.get_neighbors(u):
                g = 1.0 + u.mindistance
                h = self.heuristic(target)
                f = g + h
                if not target.is_obs:
                    if target.isopen or target in closedset:
                        if target.mindistance > g:
                            target.h_value = f
                            target.mindistance = g
                            target.previous = u
                    else:
                        target.isopen = True
                        target.h_value = f
                        target.mindistance = g
                        target.previous = u
                        heapq.heappush(openset, target)

        self.build_path()

target이 openset에 들어있는지 확인하는 것 때문에 몇 시간을 허비했다;

priority queue에서 target을 검색하면 log(n) 시간이 걸리기 때문에 n이 커지면 dijkstra 알고리즘보다 비 효율적이게 되었다.

그래서 한참을 고민했는데, 그냥 노드에 openset에 들어있는지를 표시하는 플래그를 다는 것으로 해결...

'Programming > Python' 카테고리의 다른 글

pygame 설치  (0) 2013.05.02
날씨 가져오는 스크립트의 수정  (1) 2013.04.18
날씨 가져오는 스크립트  (0) 2013.04.17
쉬워 보이는 언어 Python  (0) 2011.12.27
점프 투 파이썬(Jump to Python)  (0) 2011.12.20
Posted by Tanto