Dùng thuật toán BFS :::spoiler Code mẫu (c++) ```cpp #include <iostream> #include <vector> #include <queue> #include <climits> using namespace std; void bfs(int n, const vector<vector<int>>& graph) { vector<int> dist(n + 1, INT_MAX); dist[1] = 0; queue<int> q; q.push(1); while (!q.empty()) { int u = q.front(); q.pop(); for (int v : graph[u]) { if (dist[u] + 1 < dist[v]) { dist[v] = dist[u] + 1; q.push(v); } } } for (int i = 2; i <= n; ++i) { if (dist[i] == INT_MAX) cout << "-1 "; else cout << dist[i] << " "; } cout << endl; } int main() { int n, m; cin >> n >> m; vector<vector<int>> graph(n + 1); for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; graph[u].push_back(v); graph[v].push_back(u); } bfs(n, graph); return 0; } ``` :::
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up