Now i'm learning graphs, and i really can't get my head around BF.I mean, i uderstand the concept, but i can't get it to work in code.I don't get errors, but the function isn't working....can somewone over here please give an advice?
#include<iostream>
#include<fstream>
using namespace std;
ifstream fin("graph");
struct node{
int val;//the number that corresponds to the node
node *next_adr;//the next address (for the linked list)
};
void read(node *a[],int &n){
/* a-the array in witch i keep the nodes
n- the number of nodes */
int i,j;
node *p;
fin>>n;
while(fin>>i>>j){
p=new node;
p->val=j;
p->next_adr=a[i];
a[i]=p;
p=new node;
p->val=i;
p->next_adr=a[j];
a[j]=p;}
}
void write(node *a[],int n){//writes the nodes of the graph, just for testing the input
int i;
node *p;//i cycle with p through the list that represents the adiacent nodes to the i node
for(i=0;i<n;i++){
cout<<"The nodes adiacent to "<<i<<" are : ";
p=a[i];
while(p){
cout<<p->val<<" ";
p=p->next_adr;}
cout<<endl;}
cout<<endl;}
void breadth_first(node *a[]){
int queue[100];//I meant a FIFO structure, sorry i don't know how to say it in english
int visited[100]={0};//to know what nodes i have visited
int start=0,end=0,num;//the end and start of the FIFO structure
node *p;//cursor for the nodes
cout<<"We start the search at node : ";cin>>num;
queue[0]=num;
end++; //add the selected element to the queue
while(start<end){
p=a[queue[start]];//the first element in the FIFO structure
while(p){
if(!visited[p->val]){//if node p->val is not visited
queue[end]=p->val;//add it to the queue
end++;}
p=p->next_adr;}
cout<<a[queue[start]]->val<<" ";//output the node through i have just passed
visited[queue[start]]=1;
start++;}
}
int main(){
node *a[100]={0};//initialize a at 0 (like being global)
int n;
read(a,n);
breadth_first(a);
return 0;}
If you want to help, and don't understand some part of the source, please ask...

New Topic/Question
Reply



MultiQuote








|