#include <iostream>
#include <vector>
#include <climits>
#define forn(i, n) for (int i = 0; i < n; i++)
using namespace std;
const int oo = 2e5+1;
int t,n,m;
vector<int> clownconns[oo];
vector<int> downconns[oo];
vector<int> upconns[oo];
int values[oo];
int dp[oo];
int getdp(int node);
void cheapdfs(int node);
bool researched[oo];
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> t;
    while (t--) {
        cin >> n >> m;
        forn(i, m) {
            int a,b;
            cin >> a >> b;
            a--; b--;
            clownconns[a].push_back(b);
        }
        forn(i, n) values[i] = -1;
        forn(i, n) researched[i] = false;
        int c = 0;
        vector<int> toresearch {0};
        vector<int> next;
        while (toresearch.size() != 0) {
            for (int i: toresearch) {
                if (values[i]!=-1) continue;
                values[i]=c;
                for (int e: clownconns[i]) {
                    if (values[e]!=-1) continue;
                    next.push_back(e);
                }
            }
            c++;
            toresearch.clear();
            toresearch = next;
            next.clear();
        }
        cheapdfs(0);
        forn(i, n) dp[i]=-1;
        forn(i, n) cout << getdp(i) << " ";
        cout << endl;
        forn(i, n) clownconns[i].clear();
        forn(i, n) downconns[i].clear();
        forn(i, n) upconns[i].clear();
    }
}
void cheapdfs(int node) {
    if (researched[node]) return;
    researched[node] = true;
    for (int e: clownconns[node]) {
        if (values[e] <= values[node]) upconns[node].push_back(e);
        else {
            downconns[node].push_back(e);
            cheapdfs(e);
        }
    }
}
int getdp(int node) {
    if (dp[node]!=-1) return dp[node];
    dp[node] = values[node];
    for (int e: downconns[node]) dp[node] = min(dp[node], getdp(e));
    for (int e: upconns[node]) dp[node] = min(dp[node], values[e]);
    return dp[node];
}