﻿#include<bits/stdc++.h>
#define fo(i,a,b) for(int i=(a);i<=(b);++i)
#define fd(i,a,b) for(int i=(a);i>=(b);--i)
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
using namespace std;
typedef long long ll;
const int maxn = 1e6 + 5;
const ll mod = 1e9 + 7;
int t, m, n, k;
vector<int>e[maxn];
int d[maxn], val[maxn];
void D() {
	queue<int>q;
	q.push(1);
	while (!q.empty()) {
		int u = q.front(); q.pop();
		for (auto& v : e[u]) {
			if (d[v] == -1) {
				d[v] = d[u] + 1;
				q.push(v);
			}
		}
	}
}
int f(int u) {
	if (val[u] != -1)return val[u];
	val[u] = d[u];
	for (auto& v : e[u]) {
		if (d[v] > d[u])val[u] = min(val[u], f(v));
		else val[u] = min(val[u], d[v]);
	}
	return val[u];
}
int main() {
	IOS;
	cin >> t;
	while (t--) {
		cin >> n >> m;
		fo(i, 1, n)e[i].clear(), d[i] = val[i] = -1;
		fo(i, 1, m) {
			int u, v;
			cin >> u >> v;
			e[u].push_back(v);
		}
		d[1] = 0;
		D();
		fo(i, 1, n)cout << f(i) << ' '; cout << endl;
	}
	return 0;
}
/*

*/