Untitled
unknown
plain_text
2 years ago
769 B
2
Indexable
vector < int > adj[MAX]; int visited[ MAX ], dis[ MAX + 1 ]; queue < int > q;//queue->FIFO void BFS( int src ) { q.push(src); dis[src] = 0; visited[src] = true; printf("Level %d: %d\n", dis[src], src); while( !q.empty() ) { int v = q.front(); q.pop(); int temp; for( int i = 0 ; i < (int)adj[v].size() ; i++ ) { temp = adj[v][i]; if( !visited[temp] ) { dis[temp] = dis[v]+1; visited[temp] = true; q.push(temp); printf("Level %d: %d\n", dis[temp], temp); } } } } int main() { int e;//e = number of edges cin>>e; for( int i = 0 ; i < e ; i++ ) { int x,y; cin>>x>>y; adj[x].push_back(y); adj[y].push_back(x);//bidirectional! } BFS(1);// let node 1 be the src node! }
Editor is loading...