#include <bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
#define MOD 1000000007
#define ar array
#define fast_io ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); 

int n, m;
vector<vector<int>> adj;
vector<int> dist;
vector<bool> visited;
vector<int> res;

void dfs(int u, int p) {
	visited[u] = true;
	for (int v : adj[u]) {
		if (!visited[v] && dist[v] > dist[u])
			dfs(v, u);
	}
	for (int v : adj[u]) {
		if (dist[v] > dist[u]) {
			res[u] = min(res[u], res[v]);
		}
		else {
			res[u] = min(res[u], dist[v]);
		}
	}
	return;
}

int32_t main() {
	fast_io;
 
	int t; cin >> t;
	while (t--) {
		cin >> n >> m;
		adj.clear(); adj.resize(n);
		dist.assign(n, INT_MAX); visited.assign(n, false); res.resize(n);
		for (int i = 0; i < m; i++) {
			int u, v; cin >> u >> v; --u, --v;
			adj[u].push_back(v);
		}
		queue<int> q; q.push(0);
		dist[0] = 0; visited[0] = true;
		while (q.size()) {
			int u = q.front(); q.pop();
			for (int v : adj[u]) {
				if (!visited[v]) {
					visited[v] = true;
					dist[v] = 1 + dist[u];
					q.push(v);
				}
			}
		}
		for (int i = 0; i < n; i++) {
			res[i] = dist[i];
		}
		visited.assign(n, false);
		dfs(0, -1);
		for (int r : res) {
			cout << r << " ";
		}
		cout << endl;
	}
 
	return 0;
}