Untitled
unknown
plain_text
2 years ago
1.2 kB
2
Indexable
#include <iostream> #include <vector> #include <queue> using namespace std; const int MAXN = 1005; int v, e; vector<int> adj[MAXN]; int parent[MAXN]; bool visited[MAXN]; void addEdge(int u, int v) { adj[u].push_back(v); } void BFS(int source) { queue<int> q; // queue for storing vertices in BFS order // mark source vertex as visited and enqueue it visited[source] = true; q.push(source); parent[source] = -1; // source vertex has no parent while (!q.empty()) { int u = q.front(); q.pop(); // iterate through all the vertices adjacent to u for (int i = 0; i < adj[u].size(); i++) { int v = adj[u][i]; // if vertex v is not visited before, mark it visited and enqueue it if (!visited[v]) { visited[v] = true; q.push(v); parent[v] = u; // set parent of v as u } } } } int main() { cin >> v >> e; // add edges for (int i = 0; i < e; i++) { int u, v; cin >> u >> v; addEdge(u, v); } BFS(0); // start BFS from vertex 0 for (int i = 0; i < v; i++) { cout << "Vertex " << i << " has parent " << parent[i] << endl; } return 0; }
Editor is loading...