Demo entry 6631002

asdf

   

Submitted by sss on Jul 12, 2017 at 11:15
Language: C++. Code size: 1.2 kB.

#include<bits/stdc++.h>

using namespace std;

int n;
map<int, vector<int> > adjList;       // Considering unweighted graph

void bfs(int source){
  int dist[n+1];                     // distance vector
  memset(dist, -1, sizeof(dist));    // dist[i] = -1; means node i is unvisited
  queue<int> q;
  q.push(source);
  dist[source] = 0;
  while(!q.empty()){
    int u = q.front();
    q.pop();                        // Removing front element from queue
    for(int i = 0 ; i < adjList[u].size() ; i ++){
      int v = adjList[u][i];
      if(dist[v] == -1){            // True if v is not visited earlier
        q.push(v);                     
        dist[v] = dist[u] + 1;     
      }
    }
  }
  printf("Nodes Number    |      Distance \n");
  for(int i  = 1 ; i <= n ; i ++){
    printf("%d\t\t\t\t|\t\t%d \n", i, dist[i] ); 
  }
}


int main(){
  int edges;                    // n = number of nodes, edges = Number of edges
  scanf("%d%d",&n,&edges);
  for(int i = 0 ; i < edges ; i ++){
    int u, v;
    scanf("%d%d",&u,&v);
    adjList[u].push_back(v);
    adjList[v].push_back(u);  
  }
  int source;
  scanf("%d",&source);
  bfs(source);
}

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.

Delete this entry (admin only).