---
# System prepended metadata

title: Gọi d(i) là khoảng cách ngắn n

---

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;
}
```

:::