Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- const int MAXN = 1000;
- int used[MAXN+1], Q[MAXN], P[MAXN], G[MAXN][MAXN], N, b, e;
- void make_empty(){
- b=0;
- e=-1;
- }
- void push(int x){
- Q[++e]=x;
- }
- int pop(){
- return Q[b++];
- }
- bool emptyQ(){
- return b>e;
- }
- void BFS(int r){
- int x,y,i;
- for(i=1;i<=N;i++) used[i]=0;
- make_empty();
- push(r);
- used[r]=1;
- P[r]=0;
- while(!emptyQ()){
- x=pop();
- for(i=1;i<=G[x][0];i++){
- y=G[x][i];
- if(!used[y]){
- push(y);
- used[y]=1;
- P[y]=x;
- cout<< y <<" ";
- }
- }
- }
- }
- int main(){
- setlocale(0,"");
- int n,x,y, startV,endW, current, pathLen = 1;
- cin >> n;
- for( int i=0; i<n; i++ ){
- cin >> y >> x;
- G[x][++G[x][0]] = y;
- G[y][++G[y][0]] = x;
- }
- cin >> endW;
- cin >> startV;
- BFS(endW);
- current = startV;
- while( P[current] != endW ) {
- current = P[current];
- pathLen++;
- }
- cout << "Shortest path: " << pathLen << "\n";
- return 0;
- }
- /*
- 17
- 1 7
- 1 9
- 1 2
- 2 4
- 2 6
- 6 7
- 6 10
- 6 5
- 7 3
- 3 10
- 10 11
- 5 11
- 8 11
- 5 10
- 9 10
- 4 5
- 4 8
- 1 11
- */
Advertisement
Add Comment
Please, Sign In to add comment