내 방법은 구조체를 포함한다. 내가 입력 배열을 통해 루프 및 각 항목에 대한 노드를 생성하고 아마 표준 : : 벡터에 넣어. 그런 다음 각 노드에서 push_back()을 사용하여 해당 노드 앞에 유효한 모든 노드에 대한 참조를 유효하게 만듭니다. 그런 다음 재귀 적으로 경로를 찾습니다. 첫 번째 노드에서 시작하여 레이블을 사용하고 유효 한 첫 번째 인덱스로 이동 한 다음 해당 노드에 대해 반복 한 다음 컨트롤이 해당 지점으로 돌아올 때 유효한 다음 노드로 이동하고 동일하게 수행 한 다음 여기에서 돌아올 때, 모든 노드에서 사용 된 값을 재설정하십시오. 일치하는 항목이 없으면 false를 반환합니다.
여기에 약간의 코드가 있습니다. 각 단어의 처음과 마지막 문자가 일치하지 않는지 확인합니다. 필요에 맞게 규정 식을 수정하십시오.
#include<stdio.h>
#include<string.h>
#include<vector>
struct node{
char c1, c2;
char* str;
int used;
int ind;
std::vector<struct node*> valid;
};
int ispath_rec(std::vector<node*> &nodes, int depth, int* returnarray);
int ispath(char** value, int valuec, int* returnarray){
std::vector<node*> nodes;
for(int i = 0; i < valuec; i ++){
node* a = new node;
nodes.push_back(a);
a->used = 0;
a->str = value[i];
a->c1 = value[i][0];
a->c2 = value[i][strlen(value[i])-1];
a->ind = i;
}
for(int i = 0; i < valuec; i ++){
node* a = nodes[i];
for(int j = 0; j < valuec; j ++){
node* b = nodes[j];
if(b->c1 != a->c2 && b != a) /*b->c1 != a->c2 is the qualifying expression*/
a->valid.push_back(b);
}
}
return ispath_rec(nodes, valuec, returnarray);
}
int ispath_rec(std::vector<struct node*> &nodes, int depth, int* returnarray){
if(depth <= 0)
return 1;
for(int i = 0; i < nodes.size(); i ++){
if(nodes[i]->used == 0){
nodes[i]->used = 1;
*returnarray = nodes[i]->ind;
if(ispath_rec(nodes[i]->valid, depth-1, returnarray + 1) == 1)
return 1;
nodes[i]->used = 0;
}
}
return 0;
}
int main(){
char* tmp[] = {"hello","oeyh","aol", "loks", "sol"};
int rets[5];
if(ispath(tmp, 5, rets)){
for(int i = 0; i < 5; i ++){
printf(" %s ", tmp[rets[i]]);
}
}
}
정확하게 해밀턴의 경로 문제입니다. 여러분은 그것을 회피하지 않을 것입니다. –
단어의 순열 *을 찾고 있는지 또는 동일한 단어를 두 번 이상 사용할 수 있는지 여부를 명확히 할 수 있습니까? – NPE
@rrenaud 그건, 그들은 hamiltonian임을 증명하는 그래프에 대한 많은 클래스와 기준이 있습니다. Op는 자신의 단어 그래프를 구성하고 가능성이 있다고 판단되는 단어를 테스트 할 수 있습니다. 시작리스트는 http://en.wikipedia.org/wiki/Hamiltonian_path를 참조하십시오. – phs