Trang

Thứ Ba, 8 tháng 3, 2011

code for BFS

#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include <iomanip.h>

#define    MAX    100
#define FINPUT    "BFS2.INP"
#define FOUTPUT    "BFS2.OUT"

typedef struct    {
        int      front, rear;
        int    nodes[MAX];
} queue;

void    init(queue *Q) {
        Q->front = -1;
        Q->rear = -1;
}
int    empty(queue *Q) {
        return (Q->front==Q->rear);
}

int     full(queue *Q){
        return (Q->rear+1 == Q->front);
}

void      push(queue *Q, int x) {
        if (full(Q)) {
            cout<<"\n stack full";
            return;
        }
        Q->rear++;
        Q->nodes[Q->rear] = x;
}

int     pop(queue *Q){
        int x;
        if(empty(Q)){
        cout<< "\n Stack rong";
        return NULL;
        }
        Q->front++;
        x = Q->nodes[Q->front];
        return (x);
  }

 queue *Q;
 int n,u0,v0;
 int a[MAX][MAX];

void nhapdulieu(){
  int i,j,x;
  for(i=1;i<=n;i++)
  for(j=1;j<=n;j++) a[i][j]=0;
  i=1;
  ifstream fin(FINPUT);
  fin>>n>>u0>>v0;
  while (!fin.eof()){
    fin>>j;
    if (j==0) i++;
    else a[i][j]=1;
  }
  fin.close();
  cout<<n<<" "<<u0<<" "<<v0<<endl;
  for(i=1;i<=n;i++) {
    cout<<i<<": ";
    for(j=1;j<=n;j++)
    if(a[i][j]>0) cout<<j<<",";
    cout<<endl;
  }
}

int pred[MAX];
int found;

void BFS(int u0,int v0){
 int u,v;
 for(u=1;u<=n;u++) pred[u]=0;
 pred[u0]=-1;
 found=0;
 push(Q,u0);
 while (!empty(Q) && !found){
  /*step 1*/ u=pop(Q);
  /*step 2*/ if(u==v0) found=1;
  /*step 3*/ else
         for(v=1;v<=n;v++)
          if(a[u][v]==1 && pred[v]==0){
          /* 3.1 */ pred[v]=u;
          /* 3.2 */ push(Q,v);
          }
 } //while
}

void xuatketqua(){
 int v,m;
 int path[MAX];
 ofstream fo(FOUTPUT);
 if(!found) fo<<"No Solution";
 else{ v=v0; m=0;
    do {
      path[++m]=v;
      v=pred[v];
    }while(v!=-1);
    fo<<"Length of shorted path = "<<m<<endl;
    cout<<"Length of shorted path = "<<m<<endl;
    for(v=m;v>0;v--){
      fo<<path[v]<<"->";
      cout<<path[v]<<"->";
    }
     }
 fo.close();
}

int main(){
 clrscr();
 nhapdulieu();
 BFS(u0,v0);
 xuatketqua();
 cout<<"done!"; getch();
 return 0;
}

======================
6 1 6
2 3 0
3 5 0
5 0
5 0
6 0
4 0

Không có nhận xét nào:

Đăng nhận xét