2017-11-29 1 views
0

내가 만들고있는 게임에서 C++로 A 별 알고리즘을 구현하려고하는데 작동하지 않고 코드에 대해 놓친 내용이 있는지 또는 알고리즘 집합을 사용했기 때문에 집합을 사용했고 반환 값은 방문해야하는 노드가있는 벡터입니다. 나는 아마 이런 알고리즘을 사용한 적이 없기 때문에 나는 아마 어떤 종류의 에러를 가지고있다. 첫째 그래서스타 검색 구현 문제 C++

struct node { 
    Pos pos; 
    int f; //the sum of the distance from the goal to succcessor 
    int g; // the sum of the cost of the current plus the one from the successor 
    int h; //distance from goal to successor 

friend bool operator< (node right, node left) { 
     return (right.f < left.f); 
    } }; 



vector<node> search(Pos inicio,Pos desti){ 

    set<node> opennodes; 
    vector<node> closednodes; 
    node inici; 
    node successor; 
    inici.pos = inicio; 
    inici.h = heuristic(inicio,desti); 
    inici.g = getcost(inicio); 
    inici.f = inici.g + inici.h; 
    opennodes.insert(inici); 
    closednodes.push_back(inici); 
    while(not opennodes.empty()){ 
     node current = *(opennodes.begin()); 
     opennodes.erase(opennodes.begin()); 
     if(current.pos == desti) cerr<<"encontrao"; 
     Dir direccio; 
     for(int i = 0; i < 4;++i){ 
      if(i==0){ 
        direccio = LEFT; 

      } 
      else if(i==1){ 
        direccio = RIGHT; 
      } 
      else if(i==2){ 
        direccio = TOP; 
      } 
      else { 
        direccio = BOTTOM; 
      } 

       successor.pos = current.pos + direccio; 
       if(successor.pos == desti) return closednodes; 
       if(pos_ok(successor.pos)){ 
        successor.g = current.g + getcost(successor.pos); 
        successor.h = heuristic(successor.pos,desti); 
        successor.f = successor.g + successor.h; 

        node n1 = checkposition(successor.pos, opennodes); //I had to create two checkposition just to know if there's the node in the set or in the vector 
        node n2 = checkposition2(successor.pos, closednodes); 

        if (n1.f != -1 and n1.f < successor.f); 
        else if (n2.f != -1 and n2.f < successor.f); 
        else opennodes.insert(successor); 

       } 
     } 
      closednodes.push_back(current); 
     } 

    return closednodes; 
} 
+0

"작동하지 않습니다. 어떻게 작동하지 않습니까? – UKMonkey

+0

opennode가 비어 있지 않거나 무언가가없는 것처럼 무한 루프를 유지합니다. –

+0

opennode처럼 '결코 비어 있지 않습니다.'라는 글쎄요, 디버거가 뭐라고 말 했나요? 삽입 메소드에 중단 점을 넣고 매우 간단한 테스트 케이스를 만든 다음 예상되는 항목을 추가하는지 확인할 수 있습니다. – UKMonkey

답변

0

:

if(current.pos == desti) cerr<<"encontrao"; 

가 여기에 break 문이 있어야하지 않나요? cerr 함수는 루프를 깨뜨리지 않고 그냥 stdout에 오류 메시지를 던집니다.

그리고 while 문은 항상 4까지 실행되므로 direccio는 항상 BOTTOM으로 설정됩니다. 그 외에는 경험적으로 괜찮다고 생각합니다. 코드 구조 내에 문제가 있습니다. 디버깅을 제안하고 결과를 게시하는 것이 좋습니다.

+0

정말 맞습니다. 여기서 디버깅 할 출력 메시지 일 뿐이 었어 야합니다. 그러나 내 프로그램은 여전히 ​​실패합니다. 나는 direccio에 대한 당신의 요지를 보지 못한다. 나는 마지막 반복이 바닥에 있지만 각 "자식"(다음 셀)은 이미 설정되어 있다는 것을 안다. 그렇지 않습니까? –