グラフ構造(この場合は通りのグリッドを表す)を検索し、ノードAからノードBへのすべての可能なルートを返すCでBread-FirstSearchアルゴリズムを作成しました。
私が見つけたのは、この関数は小さなグラフ(約24ノード)では非常に高速に動作しますが、これよりも大きいものではクラッシュするということです。あまりにも多くのmallocの問題だと思ったので、関数にfree()を追加して、キューを実行しているときにスペースを削除しました。残念ながら、これで問題が解決するわけではありません。また、「メモリ不足」というエラーメッセージが表示されないことにも注意してください。そのため、何が起こっているのかわかりません...
void BFS_search(struct map *m, int start, int end){
int n = m->nb_vertice+1;
int i=0;
int num=0;
//BFS requires a queue (pile) to maintain a list of nodes to visit
struct queue {
int current_node;
int visited[n]; //cannot be a pointer! Otherwise the pointer may influence other queue structures
struct queue *suivant;
};
//Function to add a node at the end of the queue.
void addqueue (int value, struct queue *old, int * old_seen) {
int i;
if (old->suivant==NULL){
struct queue *nouveau;
nouveau = (struct queue *)malloc(sizeof(struct queue));
if (nouveau == NULL){
printf("\n\nSnap! Out of memory, exiting...\n");
exit(1);
}
nouveau->current_node = value;
for (i = 0; i <= n; ++i){
if (old_seen[i]==1)
nouveau->visited[i]=1;
else nouveau->visited[i]=0;
}
nouveau->suivant = NULL;
old->suivant=nouveau;
return;
}
else addqueue(value,old->suivant,old_seen);
}
struct queue * dequeue (struct queue *old){
struct queue *nouveau;
nouveau = (struct queue *)malloc(sizeof(struct queue));
if (nouveau == NULL){
printf("\n\nSnap! Out of memory, exiting...\n");
exit(1);
}
nouveau = old->suivant;
free(old);
return(nouveau);
}
//the actual Breadth First Search Algorithm
int BFS(struct map *m, struct queue *q, int num, int end){
int k;
q->visited[q->current_node]=1; //mark current node as visited
while(q!=NULL){
//if we reached the destination, add +1 to the counter
if (q->current_node==end){
num+=1;
}
//if not the destination, look at adjacent nodes
else {
for (k=1;k<n;++k)
if (m->dist[q->current_node][k]!=0 && q->visited[k]!=1){
addqueue(k,q,q->visited);
}
}
//if queue is empty, stop and return the number
if (q->suivant==NULL){
return(num);
}
//if queue is not empty, then move to next in queue
else
return(BFS(m,dequeue(q),num,end));
}
}
//create and initialize start structure
struct queue *debut;
debut = (struct queue *)malloc(sizeof(struct queue));
for (i = 0; i <= n; ++i)
debut->visited[i]=0;
debut->current_node=start;
debut->visited[start]=1;
debut->suivant = NULL;
num=BFS(m,debut,0,end);
printf("\nIl existe %d routes possibles! \n",num);
}
nb_vertices(ノードの数)を含むグラフのすべてのエッジとノードを格納する構造体マップと、ノードiからjまでの距離である距離行列dist[i][j]を使用していることに注意してください。 、または接続されていない場合は0。
どんな助けでも大歓迎です!使用可能なメモリの量に問題があると思います。少なくとも、メモリの問題を回避できない場合に特定のエラーメッセージを出力する方法が必要です...