Breadth First Search: Shortest Reach
- Time : O(v + e)
- Space : O(v + e)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| vector<int> bfs(int n, int m, vector<vector<int>> edges, int s) { vector<int> dis(n + 1, INT_MAX); dis[s] = 0; vector<int> adj[n + 1]; for(auto& e : edges) { int u = e[0], v = e[1]; adj[u].push_back(v); adj[v].push_back(u); } queue<int> q; q.push(s); while(!q.empty()) { auto u = q.front(); q.pop(); for(auto& v : adj[u]) { if(dis[u] + 1 < dis[v]) { dis[v] = dis[u] + 1; q.push(v); } } }
vector<int> res; for(int i = 1; i <= n; i++) { if(dis[i] == INT_MAX) res.push_back(-1); else if(dis[i] == 0) continue; else res.push_back(dis[i] * 6); } return res; }
|