Consider an undirected graph where each edge weighs 6 units.  Each of the nodes is labeled consecutively from 1 to n.

You will be given a number of queries.  For each query, you will be given a list of edges describing an undirected graph.  After you create a representation of the graph, you must determine and report the shortest distance to each of the other nodes from a given starting position using the breadth-first search algorithm (BFS).  Return an array of distances from the start node in node number order.  If a node is unreachable, return $-1$ for that node.  

Example 

The following graph is based on the listed inputs:  

$n=5$  // number of nodes 

$m=3$  // number of edges 

$edges=[1,2],[1,3],[3,4]$ 

$s=1$  // starting node  

All distances are from the start node $1$.  Outputs are calculated for distances to nodes $2$ through $5$: $[6,6,12,-1]$.  Each edge is $\boldsymbol{6}$ units, and the unreachable node $5$ has the required return distance of $-1$.  

Function Description  

Complete the bfs function in the editor below.    If a node is unreachable, its distance is $-1$.  

bfs has the following parameter(s):  

int n: the number of nodes  
int m: the number of edges  
int edges[m][2]: start and end nodes for edges
int s: the node to start traversals from  

Returns 

int[n-1]:  the distances to nodes in increasing node number order, not including the start node (-1 if a node is not reachable)  

Input Format

The first line contains an integer $\textit{q}$, the number of queries. 
Each of the following $\textit{q}$ sets of lines has the following format:

The first line contains two space-separated integers $n$ and $m$, the number of nodes and edges in the graph.  
Each line $\boldsymbol{i}$ of the $m$ subsequent lines contains two space-separated integers, $\mbox{u}$ and $v$, that describe an edge between nodes $\mbox{u}$ and $v$.  
The last line contains a single integer, $\boldsymbol{\mathrm{~S~}}$, the node number to start from.

Constraints

$1\leq q\leq10$  
$2\leq n\leq1000$  
$1\leq m\leq\frac{n\cdot(n-1)}{2}$  
$1\leq u,v,s\leq n$  

Sample Input
2
4 2
1 2
1 3
1
3 1
2 3
2

Sample Output
6 6 -1
-1 6

Explanation

We perform the following two queries:

The given graph can be represented as: 

where our start node, $\boldsymbol{\mathrm{~S~}}$, is node $1$. The shortest distances from $\boldsymbol{\mathrm{~S~}}$ to the other nodes are one edge to node $2$, one edge to node $3$, and an infinite distance to node $4$ (which it is not connected to). We then return an array of distances from node $\mbox{I}$ to nodes $2$, $3$, and $4$ (respectively): $[6,6,-1]$.  

The given graph can be represented as: 

where our start node, $\boldsymbol{\mathrm{~S~}}$, is node $2$. There is only one edge here, so node $1$ is unreachable from node $2$ and node $3$ has one edge connecting it to node $2$. We then return an array of distances from node $2$ to nodes $1$, and $3$ (respectively): $[-1,6]$.  

Note: Recall that the actual length of each edge is $\boldsymbol{6}$, and we return $-1$ as the distance to any node that is unreachable from $\boldsymbol{\mathrm{~S~}}$.

Difficulty: MEDIUM

Solutions:
from collections import defaultdict, deque

def breadth_first_search(S, N, G, L=1):
	E = defaultdict(int)
	C = {}
	for n in range(1, N + 1):
		C[n] = -1
	E[S] += 1
	C[S] = 0
	Q = deque([S])
	while Q:
		n = Q.popleft()
		for h in G[n]:
			if E[h] == 0:
				E[h] += 1
				C[h] = C[n] + L
				Q.append(h)
	return C

def main():
	T = int(input())
	for _ in range(T):
		(N, M) = [int(i) for i in input().split()]
		G = defaultdict(set)
		for _ in range(M):
			E = [int(i) for i in input().split()]
			G[E[0]].add(E[1])
			G[E[1]].add(E[0])
		S = int(input())
		D = breadth_first_search(S, N, G, 6)
		print(' '.join((str(D[n]) for n in range(1, N + 1) if n != S)))
main()


def bfs(graph, start, N):
	dist = [-1] * (N + 1)
	prev = [-1] * (N + 1)
	dist[0] = 0
	dist[start] = 0
	queue = [start]
	visited = set()
	counter = 0
	while queue:
		vertex = queue.pop(0)
		if vertex not in visited:
			visited.add(vertex)
			if vertex in graph.keys():
				S = list(graph[vertex] - visited)
				for s in S:
					if prev[s] == -1:
						prev[s] = vertex
				queue.extend(graph[vertex] - visited)
			if vertex != start:
				dist[vertex] = dist[prev[vertex]] + 6
	return ' '.join(map(str, list(filter(0 .__ne__, dist))))
T = int(input())
for i in range(0, T):
	graph = {}
	inp = input().split()
	N = int(inp[0])
	M = int(inp[1])
	for j in range(0, M):
		inp = input().split()
		edge1 = int(inp[0])
		edge2 = int(inp[1])
		if edge1 in graph:
			graph[edge1].add(edge2)
		else:
			graph[edge1] = {edge2}
		if edge2 in graph:
			graph[edge2].add(edge1)
		else:
			graph[edge2] = {edge1}
	S = int(input())
	print(bfs(graph, S, N))


def bfs(s, d):
	q = [[s, 0]]
	visited = {}
	for i in range(1, n + 1):
		visited[i] = 0
	res = [-1 for i in range(n)]
	res[s - 1] = 0
	while q:
		u = q.pop()
		if visited[u[0]] == 0:
			visited[u[0]] = 1
			res[u[0] - 1] = 6 * u[1]
			for i in d[u[0]]:
				if visited[i] == 0:
					q.insert(0, [i, u[1] + 1])
	return res
t = int(input())
for i in range(t):
	(n, m) = [int(j) for j in input().split()]
	d = {}
	for j in range(1, n + 1):
		d[j] = []
	for j in range(m):
		(n1, n2) = [int(k) for k in input().split()]
		d[n1].append(n2)
		d[n2].append(n1)
	s = int(input())
	res = bfs(s, d)
	del res[res.index(0)]
	print(' '.join(map(str, res)))


class Graph:

	def __init__(self, n):
		self.data = [[] for i in range(n)]

	def add_edge(self, a, b):
		a -= 1
		b -= 1
		self.data[a].append(b)
		self.data[b].append(a)

	def adj(self, n):
		return self.data[n]
from collections import deque

def run():
	(n, e) = list(map(int, input().strip().split(' ')))
	graph = Graph(n)
	for i in range(e):
		graph.add_edge(*list(map(int, input().strip().split(' '))))
	start = int(input()) - 1
	marked = [False] * n
	marked[start] = True
	distTo = [-1] * n
	distTo[start] = 0
	q = deque([start])
	while q:
		node = q.pop()
		nearest = graph.adj(node)
		for n in nearest:
			if marked[n]:
				continue
			marked[n] = True
			distTo[n] = 6 + distTo[node]
			q.appendleft(n)
	distTo.remove(0)
	print(' '.join(map(str, distTo)))
t = int(input())
for i in range(t):
	run()


from collections import deque

def bfs(graph, start, end):
	queue = deque()
	seen = {}
	if end in graph[start]:
		return 6
	for key in graph[start].keys():
		seen[key] = True
		queue.append((key, 6))
	while len(queue) > 0:
		(key, dist) = queue.popleft()
		if end in graph[key]:
			return dist + 6
		for nkey in graph[key].keys():
			if nkey in seen:
				continue
			seen[nkey] = True
			queue.append((nkey, dist + 6))
	return -1
tests = int(input())
c = 0
while c < tests:
	c += 1
	[nodes, edges] = [int(x) for x in input().split(' ')]
	graph = {}
	for idx in range(1, nodes + 1):
		graph[idx] = {}
	e = 0
	while e < edges:
		e += 1
		[idx, jdx] = [int(x) for x in input().split(' ')]
		graph[idx][jdx] = True
		graph[jdx][idx] = True
	s = int(input())
	line = ''
	for idx in range(1, nodes + 1):
		if idx == s:
			continue
		line += str(bfs(graph, s, idx)) + ' '
	print(line[:-1])


from collections import deque

class Vertex:

	def __init__(self, id):
		self.id = id
		self.visited = False
		self.score = -1
		self.edges = []

	def __str__(self):
		return str(self.score)

	def addEdge(self, to):
		if to not in self.edges:
			self.edges.append(to)

def bfs(g, v):
	v.visited = True
	v.score = 0
	q = deque([])
	q.append(v)
	while len(q) > 0:
		for n in [graph[x] for x in q[0].edges]:
			if not n.visited:
				n.score = q[0].score + 6
				n.visited = True
				q.append(n)
		q.popleft()
T = int(input())
for t in range(T):
	(N, M) = map(int, input().split())
	graph = {n: Vertex(n) for n in range(1, N + 1)}
	for m in range(M):
		(x, y) = map(int, input().split())
		graph[x].addEdge(y)
		graph[y].addEdge(x)
	S = int(input())
	bfs(graph, graph[S])
	graph.pop(S)
	print(' '.join(map(str, graph.values())))


T = int(input())
for _ in range(T):
	(N, M) = [int(x) for x in input().split()]
	nodes = []
	for i in range(N):
		nodes.append(set())
	marked = [False] * N
	dist = [-1] * N
	for _ in range(M):
		(s, t) = [int(x) - 1 for x in input().split()]
		nodes[s].add(t)
		nodes[t].add(s)
	s = int(input()) - 1
	dist[s] = 0
	q = [s]
	while q:
		x = q.pop(0)
		for y in nodes[x]:
			if not marked[y]:
				marked[y] = True
				q.append(y)
				dist[y] = dist[x] + 6
	dist.pop(s)
	print(*dist)


def shortest_reach(G, S):
	R = [-1 for i in range(len(G))]
	R[S] = 0
	Visited = [False for i in range(len(G))]
	Q = []
	Q.append((S, G[S]))
	while len(Q) > 0:
		node = Q.pop(0)
		s = node[0]
		vs = node[1]
		for v in vs:
			Visited[v] = True
			if R[v] == -1:
				R[v] = R[s] + 6
			else:
				R[v] = min(R[v], R[s] + 6)
		for v in vs:
			uv = []
			for x in G[v]:
				if not Visited[x]:
					uv.append(x)
			if len(uv) > 0:
				Q.append((v, uv))
	return R
T = int(input())
for x in range(T):
	l = input().split()
	(N, M) = (int(l[0]), int(l[1]))
	A = [[] for i in range(N)]
	for i in range(M):
		l = input().split()
		(v1, v2) = (int(l[0]) - 1, int(l[1]) - 1)
		if v2 not in A[v1]:
			A[v1].append(v2)
		if v1 not in A[v2]:
			A[v2].append(v1)
	for (i, v) in enumerate(A):
		A[i] = sorted(A[i])
	S = int(input()) - 1
	path = shortest_reach(A, S)
	del path[S]
	print(' '.join(map(str, path)))


import heapq
for i in range(int(input())):
	(V, E) = map(int, input().split())
	edge = [[] for _ in range(V)]
	for _ in range(E):
		(fr, to) = map(lambda x: int(x) - 1, input().split())
		edge[fr].append(to)
		edge[to].append(fr)
	s = int(input()) - 1
	dist = [float('inf')] * V
	dist[s] = 0
	pque = [(0, s)]
	while pque:
		(now_dist, now_node) = heapq.heappop(pque)
		if dist[now_node] < now_dist:
			continue
		for next_node in edge[now_node]:
			if now_dist + 6 < dist[next_node]:
				dist[next_node] = now_dist + 6
				heapq.heappush(pque, (dist[next_node], next_node))
	print(*[-1 if x == float('inf') else x for x in dist if x])


import fileinput
input_list = []
for line in fileinput.input():
	input_list.append([x for x in line.strip().split(' ')])
T = int(input_list[0][0])
cases = input_list[1:]
(i, el) = (0, 6)

def grapher(edges, S):
	(ed, graph) = ([], {S: []})
	for pair in edges:
		(node1, node2) = (pair[0], pair[1])
		if node1 not in graph:
			graph[node1] = [node2]
		elif node2 not in graph[node1]:
			graph[node1].append(node2)
		if node2 not in graph:
			graph[node2] = [node1]
		elif node1 not in graph[node2]:
			graph[node2].append(node1)
	queue = [S]
	while queue:
		k = queue.pop(0)
		for x in graph[k]:
			if x not in queue:
				queue.append(x)
			graph[x].remove(k)
	return graph

def calc(key, queue, deg):
	deg += 1
	q = []
	if key in queue:
		return deg
	else:
		for x in queue:
			if x in graph:
				q += graph[x]
		if q:
			deg = calc(key, q, deg)
		else:
			return -1
	return deg
for t in range(T):
	(N, M) = (int(cases[i][0]), int(cases[i][1]))
	S = cases[i + 1 + M][0]
	edges = cases[i + 1:i + 1 + M]
	graph = grapher(edges, S)
	res = ''
	for x in range(1, N + 1):
		key = str(x)
		if key not in graph:
			res += '-1 '
		elif key != S:
			dist = calc(key, graph[S], 0)
			res += str(dist * el) + ' ' if dist > 0 else str(dist) + ' '
	print(res.strip())
	i += 2 + M


G = []
D = []
C = []

def BFS(v):
	Q = [v]
	while len(Q) > 0:
		v = Q.pop(0)
		for u in G[v]:
			if not C[u]:
				D[u] = D[v] + 6
				Q.append(u)
				C[u] = 1
		C[v] = 2
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split()))
	G = [[] for _ in range(n + 1)]
	D = [-1] * (n + 1)
	C = [0] * (n + 1)
	for _ in range(m):
		(x, y) = list(map(int, input().split()))
		G[x].append(y)
		G[y].append(x)
	s = int(input())
	D[s] = 0
	BFS(s)
	print(' '.join(list(map(str, D[1:s] + D[s + 1:]))))


from queue import Queue
t = int(input())
for _ in range(t):
	(n, m) = list(map(int, input().split(' ')))
	graph = {v: {'edges': [], 'distance': float('inf')} for v in range(1, n + 1)}
	for i in range(m):
		(x, y) = list(map(int, input().split(' ')))
		graph[x]['edges'].append(y)
		graph[y]['edges'].append(x)
	starting_point = int(input())
	graph[starting_point]['distance'] = 0
	q = Queue()
	q.put(starting_point)
	while not q.empty():
		current_node = q.get()
		distance_to_current_node = graph[current_node]['distance']
		for neighbor in graph[current_node]['edges']:
			distance_to_neighbor_from_current_node = distance_to_current_node + 6
			if distance_to_neighbor_from_current_node < graph[neighbor]['distance']:
				graph[neighbor]['distance'] = distance_to_neighbor_from_current_node
				q.put(neighbor)
	print(' '.join([str(graph[v]['distance']) if graph[v]['distance'] != float('inf') else '-1' for v in range(1, n + 1) if v != starting_point]))


for _ in range(int(input())):
	(N, M) = list(map(int, input().split(' ')))
	V = {}
	for v in range(1, N + 1):
		V[v] = []
	for m in range(M):
		(x, y) = list(map(int, input().split(' ')))
		V[x].append(y)
		V[y].append(x)
	S = int(input())
	Q = [S]
	D = {}
	D[S] = 0
	while len(Q) > 0:
		d = D[Q[0]]
		u = Q[0]
		Q = Q[1:]
		for v in V[u]:
			if not v in D:
				D[v] = d + 6
				Q.append(v)
	res = []
	for x in V.keys():
		if not x in D:
			res.append('-1')
		elif D[x] > 0:
			res.append(str(D[x]))
	print(' '.join(res))


def walk_graph(numnodes, edges, startnode):
	nodes = [-1] * (numnodes + 1)
	nodes[startnode] = 0
	next_nodes = [startnode]
	while next_nodes:
		these_nodes = next_nodes
		next_nodes = []
		for n in these_nodes:
			for e in edges[n]:
				if nodes[e[0]] == -1 or nodes[e[0]] > nodes[n] + e[1]:
					nodes[e[0]] = nodes[n] + e[1]
					next_nodes.append(e[0])
	return nodes

def main():
	WEIGHT = 6
	T = int(input())
	for i in range(T):
		(N, M) = tuple(map(int, input().split()))
		edges = [set() for i in range(N + 1)]
		for m in range(M):
			(x, y) = tuple(map(int, input().split()))
			edges[x].add((y, WEIGHT))
			edges[y].add((x, WEIGHT))
		S = int(input())
		nodes = walk_graph(N, edges, S)
		nodes.pop(S)
		print(' '.join([str(nodes[n]) for n in range(1, len(nodes))]))
main()


import collections
import io

class Node:

	def __init__(self, index):
		self.index = index
		self.relationship_indexes = set()
		self.distance = -1
		self.previous_node = None

def traverse(start_node, graph):
	index_queue = collections.deque()
	index_queue.appendleft(start_node.index)
	current_node = graph[0]
	while index_queue:
		tmp_node = graph[index_queue.pop()]
		tmp_node.previous_node = current_node
		current_node = tmp_node
		for edge_index in current_node.relationship_indexes:
			edge_node = graph[edge_index]
			if not edge_node.previous_node:
				edge_node.previous_node = current_node
				edge_node.distance = max(0, current_node.distance) + 6
				index_queue.appendleft(edge_index)
T = int(input().strip())
for test_case in range(T):
	(N, M) = [int(_) for _ in input().split()]
	graph = [Node(i) for i in range(N + 1)]
	for (node_a, node_b) in [[int(x) for x in input().split()] for i in range(M)]:
		graph[node_a].relationship_indexes.add(node_b)
		graph[node_b].relationship_indexes.add(node_a)
	S = int(input())
	start_node = graph[S]
	traverse(start_node, graph)
	print(' '.join((str(_.distance) for _ in graph[1:] if _ is not start_node)))


EDGE_WEIGHT = 6

class Graph:

	def __init__(self, num_nodes):
		self.num_nodes = num_nodes
		self.node_to_edges = {}
		for node in range(1, num_nodes + 1):
			self.node_to_edges[node] = set()

	def add_edge(self, node1, node2):
		self.add_directed_edge(node1, node2)
		self.add_directed_edge(node2, node1)

	def add_directed_edge(self, start, end):
		self.node_to_edges[start].add(end)

	def bfs_distances(self, start):
		distances = [-1] * self.num_nodes
		seen = {start}
		queue = [(start, 0)]
		while len(queue) > 0:
			(current_node, current_level) = queue.pop(0)
			self.__update_queue(queue, current_node, current_level, seen)
			if current_level != 0:
				distances[current_node - 1] = current_level * EDGE_WEIGHT
		distances.pop(start - 1)
		return distances

	def __update_queue(self, queue, current_node, current_level, seen):
		for node in self.node_to_edges[current_node]:
			if node not in seen:
				queue.append((node, current_level + 1))
				seen.add(node)

	def __str__(self):
		return str(self.node_to_edges)

def read_tuple():
	return [int(x) for x in input().split()]
num_tests = int(input())
for _ in range(num_tests):
	(n, m) = read_tuple()
	graph = Graph(n)
	for _ in range(m):
		graph.add_edge(*read_tuple())
	starting_node = int(input())
	distances = graph.bfs_distances(starting_node)
	print(' '.join((str(d) for d in distances)))


class Node:

	def __init__(self, name):
		self.name = name
		self.connected = set()
		self.distance = -1

	def connect(self, other):
		self.connected.add(other)
		other.connected.add(self)
test_size = int(input().strip())
for i in range(0, test_size):
	test_case = input().strip().split(' ')
	num_of_nodes = int(test_case[0])
	num_of_edges = int(test_case[1])
	nodes = []
	nodes.append(Node('empty'))
	for n in range(1, num_of_nodes + 1):
		nodes.append(Node(n))
	for j in range(0, num_of_edges):
		line = input().strip().split(' ')
		node1 = nodes[int(line[0])]
		node2 = nodes[int(line[1])]
		node1.connect(node2)
	root_name = int(input().strip())
	root = nodes[root_name]
	root.distance = 0
	visited = set()
	queue = []
	queue.append(root)
	visited.add(root)
	while len(queue) > 0:
		out = queue.pop(0)
		for neighbor in out.connected:
			if neighbor not in visited:
				neighbor.distance = out.distance + 6
				visited.add(neighbor)
				queue.append(neighbor)
	print_str = ''
	for i in range(1, num_of_nodes + 1):
		if i != root_name:
			print_str = print_str + str(nodes[i].distance) + ' '
	print(print_str.strip())


from collections import deque

def bfs(start, adj_map):
	visited = {}
	parent = {}
	visited[start] = True
	parent[start] = None
	Q = deque()
	Q.append(start)
	while len(Q):
		node = Q.popleft()
		if node in adj_map:
			for child in adj_map[node]:
				if child not in visited:
					parent[child] = node
					visited[child] = True
					Q.append(child)
	return parent

def calculate_distance(node, start, parents):
	if node not in parents:
		return -1
	else:
		count = 0
		x = node
		while parents[x]:
			count += 6
			x = parents[x]
		return count
T = int(input())
for _ in range(T):
	(N, M) = [int(x) for x in input().split()]
	adj_map = {}
	nodes = set()
	for _ in range(M):
		(e1, e2) = [int(x) for x in input().split()]
		if e1 in adj_map:
			adj_map[e1].add(e2)
		else:
			adj_map[e1] = set([e2])
		if e2 in adj_map:
			adj_map[e2].add(e1)
		else:
			adj_map[e2] = set([e1])
		nodes.add(e1)
		nodes.add(e2)
	start = int(input())
	if start in nodes:
		nodes.remove(start)
	parents = bfs(start, adj_map)
	dists = []
	for i in range(1, N + 1):
		if i == start:
			continue
		elif i not in nodes:
			dists.append(-1)
		else:
			dists.append(calculate_distance(i, start, parents))
	print(' '.join((str(x) for x in dists)))


from collections import deque
from operator import itemgetter

def create_graph():
	data = input().split()
	num_of_nodes = int(data[0])
	num_of_edges = int(data[1])
	graph = {}
	for x in range(1, num_of_nodes + 1, 1):
		graph[x] = []
	for i in range(num_of_edges):
		data = input().split()
		fro_m = int(data[0])
		to = int(data[1])
		if fro_m in graph[to] or to in graph[fro_m]:
			continue
		else:
			graph[to].append(fro_m)
			graph[fro_m].append(to)
	return graph

def do_level_bfs(graph, start_node):
	d = deque()
	d.appendleft(start_node)
	out = []
	new_level = False
	nodes_in_level = len(graph[start_node])
	nodes_next_level = 0
	temp = d.pop()
	out.append(temp)
	for i in graph[temp]:
		d.appendleft(i)
	while len(d) != 0:
		temp = d.pop()
		if nodes_in_level == 0:
			nodes_in_level = nodes_next_level
			nodes_next_level = 0
			out.append('level complete')
		out.append(temp)
		for i in graph[temp]:
			if i not in out and i not in d:
				nodes_next_level += 1
				d.appendleft(i)
		nodes_in_level -= 1
	return out

def sort_and_print(level_bfs, key_list):
	level_comp_count = 1
	to_sort_by_indices = {}
	for i in level_bfs[1:]:
		if i == 'level complete':
			level_comp_count += 1
			continue
		to_sort_by_indices[i] = 6 * level_comp_count
	key_list = sorted(key_list)
	final_output = []
	for i in key_list:
		if i not in to_sort_by_indices:
			final_output.append('-1')
		else:
			final_output.append(str(to_sort_by_indices[i]))
	print(' '.join(final_output))
num_test = int(input())
for i in range(num_test):
	graph = create_graph()
	start_node = int(input())
	level_bfs = do_level_bfs(graph, start_node)
	key_list = list(graph.keys())
	key_list.remove(start_node)
	sort_and_print(level_bfs, key_list)


test_cases = int(input().strip())
for test in range(test_cases):
	(nodes, edges) = [int(item) for item in input().strip().split()]
	graph = {node + 1: set() for node in range(nodes)}
	for edge in range(edges):
		(from_, to) = [int(item) for item in input().strip().split()]
		graph[from_].add(to)
		graph[to].add(from_)
	source = int(input().strip())
	node_queue = [source]
	queue_idx = 0
	distances = {source: 0}
	while queue_idx < len(node_queue):
		node = node_queue[queue_idx]
		distance = distances[node] + 6
		queue_idx += 1
		for child in graph[node]:
			if child not in distances:
				node_queue.append(child)
				distances[child] = distance
	print(' '.join((str(distances[j] if j in distances else -1) for j in range(1, nodes + 1) if j != source)))


def bfsDist(g, s):
	result = [-1] * len(g)
	result[s] = 0
	q = [s]
	while len(q) > 0:
		v = q[0]
		q = q[1:]
		for neib in g[v]:
			if result[neib] < 0:
				result[neib] = result[v] + 6
				q += [neib]
	return result
t = int(input())
for _ in range(t):
	(n, m) = [int(x) for x in input().split()]
	g = [[] for i in range(n)]
	for __ in range(m):
		(f, t) = [int(x) - 1 for x in input().split()]
		g[f] += [t]
		g[t] += [f]
	s = int(input()) - 1
	r = bfsDist(g, s)
	print(' '.join((str(x) for x in r if x != 0)))


import sys

def bfsshortreach(adj, s):
	dist = [sys.maxsize] * len(adj)
	dist[s - 1] = 0
	unvisited = [x for x in range(1, len(adj) + 1)]
	q = [s]
	while len(q) != 0:
		curr_node = q.pop(0)
		unvisited.remove(curr_node)
		for neighbor in adj[curr_node]:
			if neighbor in unvisited:
				if neighbor not in q:
					q.append(neighbor)
				test_distance = dist[curr_node - 1] + 6
				if test_distance < dist[neighbor - 1]:
					dist[neighbor - 1] = test_distance
	dist = [-1 if x == sys.maxsize else x for x in dist]
	return dist
num_cases = int(input())
for i in range(num_cases):
	(nodes, edges) = tuple([int(x) for x in input().split()])
	adj = {}
	for node in range(1, nodes + 1):
		adj[node] = set()
	for edge in range(edges):
		(n1, n2) = tuple([int(x) for x in input().split()])
		adj[n1].add(n2)
		adj[n2].add(n1)
	start = int(input())
	dist = bfsshortreach(adj, start)
	print(' '.join([str(x) for x in dist[:start - 1] + dist[start:]]))


from collections import defaultdict
import heapq
EDGE_WEIGHT = 6

def parse_case():
	(nv, ne) = list(map(int, input().split()))
	edges = list()
	for e in range(ne):
		edges.append(list(map(int, input().split())))
	return (Graph(nv, edges), int(input()))

class Graph:

	def __init__(self, n, edges):
		self.n = n
		neighbours = defaultdict(set)
		for (x, y) in edges:
			neighbours[x].add(y)
			neighbours[y].add(x)
		self.neighbours = neighbours

	def get_neighbours(self, x):
		return self.neighbours[x]

	def get_n(self):
		return self.n

def short_dists(g, s):
	dists = defaultdict(lambda : -1)
	dists[s] = 0
	visited = set()
	tovisit = []
	heapq.heappush(tovisit, (dists[s], s))
	while tovisit:
		(_, v) = heapq.heappop(tovisit)
		distv = dists[v]
		if v in visited:
			continue
		for n in g.get_neighbours(v):
			if dists[n] == -1 or distv + EDGE_WEIGHT < dists[n]:
				dists[n] = distv + EDGE_WEIGHT
			heapq.heappush(tovisit, (dists[n], n))
		visited.add(v)
	return dists
T = int(input())
for t in range(T):
	(g, s) = parse_case()
	dists = short_dists(g, s)
	print(' '.join(list((str(dists[v]) for v in range(1, g.get_n() + 1) if v != s))))


def create_graph(n):
	return {i: {} for i in range(1, n + 1)}

def add_directed_edge(G, x, y, weight):
	if not x in G:
		G[x] = {}
	G[x][y] = weight

def add_edge(G, x, y):
	add_directed_edge(G, x, y, 6)
	add_directed_edge(G, y, x, 6)
	return G

def breadth_first_search_tree(G, s):
	visited = []
	frontier = [(s, s, 0)]
	tree = {}
	while len(frontier) > 0:
		f = frontier.pop(0)
		if not f[0] in visited:
			visited.append(f[0])
			tree[f[0]] = (f[1], f[2])
			for q in G[f[0]]:
				if not q in visited:
					frontier.append((q, f[0], tree[f[0]][1] + G[q][f[0]]))
	return tree
T = int(input())
for t in range(T):
	[N, M] = [int(n) for n in input().split(' ')]
	G = create_graph(N)
	for m in range(M):
		[x, y] = [int(n) for n in input().split(' ')]
		add_edge(G, x, y)
	S = int(input())
	tree = breadth_first_search_tree(G, S)
	out_str = ''
	for n in range(1, N + 1):
		if n != S:
			if n in tree:
				out_str += str(tree[n][1])
			else:
				out_str += '-1'
			if n != N:
				out_str += ' '
	print(out_str)


T = int(input())

def BFS(G, S, N):
	Q = []
	pi = [-1 for k in range(N + 1)]
	col = [0 for k in range(N + 1)]
	pi[S] = 0
	col[S] = 1
	Q.append(S)
	while len(Q) > 0:
		x = Q.pop(0)
		col[x] += 1
		for e in range(1, len(G[x])):
			if G[x][e] and col[e] == 0:
				Q.append(e)
				col[e] += 1
				pi[e] = pi[x] + 6
	print((pi[1:S] + pi[S + 1:]).__str__().replace('[', '').replace(']', '').replace(',', ''))
for u in range(T):
	(N, M) = map(int, input().split())
	G = [[0 for x in range(N + 1)] for x in range(N + 1)]
	for m in range(M):
		(x, y) = map(int, input().split())
		G[x][y] = G[y][x] = 6
	S = int(input())
	BFS(G, S, N)


from collections import defaultdict, deque
n_cases = int(input())
for _ in range(n_cases):
	(n_nodes, n_edges) = (int(s) for s in input().split())
	graph = {node: set() for node in range(1, n_nodes + 1)}
	for _ in range(n_edges):
		(a, b) = (int(s) for s in input().split())
		graph[a].add(b)
		graph[b].add(a)
	start = int(input())
	hops = {node: -1 for node in graph}
	q = deque()
	visited = set()
	hops[start] = 0
	q.append(start)
	while q:
		current = q.popleft()
		visited.add(current)
		for neighbor in graph[current]:
			if neighbor in visited:
				continue
			old_hops = hops[neighbor]
			new_hops = hops[current] + 1
			if old_hops == -1 or new_hops < old_hops:
				hops[neighbor] = new_hops
			q.append(neighbor)
	paths = [hop for (node, hop) in hops.items() if node != start]
	print(' '.join((str(n) for n in map(lambda x: x if x == -1 else x * 6, paths))))


cases = int(input())

def run():
	(N, M) = list(map(int, input().split()))
	nodes = [n for n in range(1, N + 1)]
	edges = {n: set() for n in nodes}
	for i in range(M):
		(s, t) = list(map(int, input().split()))
		edges[s].add(t)
		edges[t].add(s)
	start = int(input())
	distances = {n: -1 for n in nodes}
	visited = set()
	queue = [[start, 0]]
	while queue:
		(node, distance) = queue.pop()
		if node in visited:
			continue
		distances[node] = distance
		visited.add(node)
		next_neighbors = [node for node in edges[node]]
		queue = [[n, distance + 6] for n in next_neighbors] + queue
	return ' '.join(map(str, [distances[n] for n in nodes if n != start]))
for i in range(cases):
	print(run())


DIST_EDGE = 6

class vertex:

	def __init__(self):
		self.key = 0
		self.color = None
		self.parent = None
		self.distance = float('inf')

def BFS(G, s):
	frontier = []
	vtx_list = [0] * len(G.keys())
	for key in G:
		new_vtx = vertex()
		new_vtx.color = 1
		new_vtx.key = key
		vtx_list[key] = new_vtx
	vtx_list[s].color = 0
	vtx_list[s].distance = 0
	frontier.append(s)
	while frontier:
		u = frontier.pop(0)
		for idx in G[u]:
			if vtx_list[idx].color == 1:
				vtx_list[idx].color = 0
				vtx_list[idx].distance = vtx_list[u].distance + DIST_EDGE
				vtx_list[idx].parent = vtx_list[u]
				frontier.append(idx)
		vtx_list[u].color = 2
	return vtx_list

def shortest_path(s, v, n):
	if s.key == v.key:
		return str(n)
	elif v.parent == None:
		return str(-1)
	else:
		return shortest_path(s, v.parent, n + DIST_EDGE)

def main():
	n = int(input())
	for i in range(0, n):
		myin = input().split()
		num_vtx = int(myin[0])
		num_edg = int(myin[1])
		G = {}
		for i in range(0, num_vtx):
			G[i] = []
		for i in range(0, num_edg):
			myin2 = [int(x) - 1 for x in input().split()]
			G[myin2[0]].append(myin2[1])
			G[myin2[1]].append(myin2[0])
		s = int(input()) - 1
		vtx_list = BFS(G, s)
		outlist = []
		for (i, vertex) in enumerate(vtx_list):
			if i != s:
				temp = shortest_path(vtx_list[s], vertex, 0)
				outlist.append(str(temp))
		print(' '.join(outlist))
main()


from collections import defaultdict, deque

def breadth_first_search(S, N, G, L=1):
	E = defaultdict(int)
	C = {}
	for n in range(1, N + 1):
		C[n] = -1
	E[S] += 1
	C[S] = 0
	Q = deque([S])
	while Q:
		n = Q.popleft()
		for h in G[n]:
			if E[h] == 0:
				E[h] += 1
				C[h] = C[n] + L
				Q.append(h)
	return C

def main():
	T = int(input())
	for _ in range(T):
		(N, M) = [int(i) for i in input().split()]
		G = defaultdict(set)
		for _ in range(M):
			E = [int(i) for i in input().split()]
			G[E[0]].add(E[1])
			G[E[1]].add(E[0])
		S = int(input())
		D = breadth_first_search(S, N, G, 6)
		print(' '.join((str(D[n]) for n in range(1, N + 1) if n != S)))
main()


ncases = int(input())
weight = 6
for iteration in range(ncases):
	(nnodes, nedges) = input().split()
	adj = {}
	for node in range(1, int(nnodes) + 1):
		adj[node] = []
	for nn in range(int(nedges)):
		(left, right) = map(int, input().split())
		adj[left].append(right)
		adj[right].append(left)
	start = int(input())
	queue = [start]
	visited = [start]
	length = {start: 0}
	while queue != []:
		current = queue.pop(0)
		neighbors = adj[current]
		for n in neighbors:
			if n not in visited:
				queue.append(n)
				visited.append(n)
			if n in length:
				length[n] = min(length[current] + weight, length[n])
			else:
				length[n] = length[current] + weight
	for i in [x for x in range(1, int(nnodes))]:
		if i != start:
			if i in length:
				print(length[i], end=' ')
			else:
				print(-1, end=' ')
	if int(nnodes) != start:
		if int(nnodes) in length:
			print(length[int(nnodes)])
		else:
			print(-1)


from collections import defaultdict
from collections import deque

def BFS(graph, n, m, edge_len, sdist, start_node):
	visited = set([start_node])
	queue = deque([(start_node, 1)])
	while len(queue) != 0:
		(node, depth) = queue.popleft()
		for neighbor in graph.get(node, []):
			if neighbor not in visited:
				sdist[neighbor - 1] = depth * edge_len
				visited.add(neighbor)
				queue.append((neighbor, depth + 1))
t = int(input())
for i in range(t):
	graph = defaultdict(set)
	(n, m) = [int(x) for x in input().split()]
	for j in range(m):
		(snode, enode) = [int(x) for x in input().split()]
		graph[snode].add(enode)
		graph[enode].add(snode)
	start_node = int(input())
	sdist = [-1] * n
	edge_len = 6
	BFS(graph, n, m, edge_len, sdist, start_node)
	print(' '.join([str(d) for (k, d) in enumerate(sdist) if k != start_node - 1]))


def toStr(x):
	if x == float('inf'):
		return str(-1)
	return str(x)
total = int(input())
for x in range(total):
	(n, m) = map(lambda x: int(x), input().split())
	nodes = list(range(1, n + 1))
	nodesDict = {}
	for u in nodes:
		nodesDict[u] = {'distance': float('inf'), 'edges': set([])}
	for e in range(m):
		(e1, e2) = tuple(map(lambda x: int(x), input().split()))
		nodesDict[e1]['edges'].add(e2)
		nodesDict[e2]['edges'].add(e1)
	s = int(input())
	nodesDict[s]['distance'] = 0
	nodes.remove(s)
	history = set([s])
	q = list(nodesDict[s]['edges'])
	while len(q) != 0:
		v = q.pop(0)
		if v not in history:
			nodesDict[v]['distance'] = min([nodesDict[w]['distance'] for w in nodesDict[v]['edges']]) + 6
			history.add(v)
			q.extend(nodesDict[v]['edges'].copy())
	print(str.join(' ', [toStr(nodesDict[i]['distance']) for i in nodes]))


from collections import defaultdict
from collections import deque

def make_adj_list(edges):
	graph = defaultdict(set)
	for (s, e) in edges:
		graph[s].add(e)
		graph[e].add(s)
	return graph

def calc_distances(graph, s, num_nodes):
	seen = set((s,))
	q = deque([[s, 0]])
	distances = [-1 for _ in range(num_nodes)]
	while q:
		(node, dist) = q.pop()
		distances[node] = dist
		for adj in graph[node]:
			if adj not in seen:
				seen.add(adj)
				q.appendleft([adj, dist + 6])
	del distances[s]
	return distances
i = int(input())
for _ in range(i):
	(n, m) = [int(el) for el in input().split()]
	edges = []
	for _ in range(m):
		(s, e) = [int(el) for el in input().split()]
		edges.append((s - 1, e - 1))
	start = int(input())
	graph = make_adj_list(edges)
	distances = calc_distances(graph, start - 1, n)
	print(' '.join((str(el) for el in distances)))


__author__ = 'akshat'
import copy

class graph:

	def __init__(self, nodes, edges):
		self.nodes = {}
		self.edges = {}
		for i in range(1, nodes + 1):
			self.nodes[i] = set()
		self.edge_count = edges

	def add_edge(self, node1, node2, length=6):
		self.nodes[node1].add(node2)
		self.nodes[node2].add(node1)
		self.edges[node1, node2] = length
		self.edges[node2, node1] = length

	def __str__(self):
		return str(self.nodes)

	def bfs(self, start):
		(visited, queue) = (set(), [start])
		g = copy.deepcopy(self.nodes)
		path_length = [-1 for i in range(len(self.nodes) + 1)]
		path_length[start] = 0
		while queue:
			vertex = queue.pop(0)
			if vertex not in visited:
				visited.add(vertex)
				added = g[vertex] - visited
				for i in added:
					if path_length[i] == -1:
						path_length[i] = path_length[vertex] + self.edges[i, vertex]
					else:
						path_length[i] = min(path_length[i], path_length[vertex] + self.edges[i, vertex])
				queue.extend(g[vertex] - visited)
		return path_length[1:]
test_cases = int(input())
for _ in range(test_cases):
	(nodes, edges) = map(int, input().split())
	g = graph(nodes, edges)
	for _ in range(edges):
		(node1, node2) = map(int, input().split())
		g.add_edge(node1, node2)
	start = int(input())
	lst = g.bfs(start)
	lst.pop(start - 1)
	print(' '.join(map(str, lst)))


w = 6

def bfsearch(graph, toSearch, answers):
	if len(toSearch) > 0:
		node = toSearch.pop(0)
		for i in graph[node]:
			if not i in answers:
				answers[i] = answers[node] + w
				toSearch.append(i)
		bfsearch(graph, toSearch, answers)
T = int(input())
for i in range(T):
	(N, M) = map(int, input().split())
	graph = {}
	for j in range(1, N + 1):
		graph[j] = []
	for j in range(M):
		(x, y) = map(int, input().split())
		graph[x].append(y)
		graph[y].append(x)
	s = int(input())
	answers = {}
	answers[s] = 0
	toSearch = []
	for j in graph[s]:
		answers[j] = w
		toSearch.append(j)
	bfsearch(graph, toSearch, answers)
	output = ''
	for j in range(1, N + 1):
		if j != s:
			if j in answers:
				output += str(answers[j]) + ' '
			else:
				output += '-1 '
	print(output.strip())


t = int(input())
for _ in range(t):
	(n, e) = input().split()
	adj = []
	for i in range(0, int(n) + 1):
		adj.append([])
	for i in range(int(e)):
		(x, y) = map(int, input().split())
		adj[x].append(y)
		adj[y].append(x)
	s = int(input())
	l = [-1] * (int(n) + 1)
	l[0] = 0
	l[s] = 0
	visited = [s]
	queue = [s]
	while queue != []:
		x = queue.pop()
		for y in adj[x]:
			if l[y] == -1 or l[y] > l[x] + 6:
				l[y] = l[x] + 6
				visited.append(y)
				queue.append(y)
	for i in range(len(l)):
		if l[i] != 0:
			if i != len(l) - 1:
				print(l[i], end=' ')
			else:
				print(l[i])


from collections import deque

def BFS(edges, S):
	N = len(edges)
	nodes = [-1] * N
	nodes[S] = 0
	q = deque()
	q.append(S)
	while q:
		u = q.popleft()
		for i in range(N):
			if edges[u][i] and i != u and (nodes[i] == -1):
				nodes[i] = 6 + nodes[u]
				q.append(i)
	del nodes[S]
	print(' '.join((str(x) for x in nodes)))
T = int(input())
for _ in range(T):
	(N, M) = (int(x) for x in input().split())
	edges = [[False] * N for _ in range(N)]
	for _ in range(M):
		(x, y) = (int(x) - 1 for x in input().split())
		edges[x][y] = edges[y][x] = True
	S = int(input()) - 1
	BFS(edges, S)


from collections import defaultdict

def print_seq(seq):
	print(' '.join(('{}'.format(v) for v in seq)))

def component(graph, start):
	(visited, queue) = (set(), [start])
	while queue:
		vertex = queue.pop(0)
		if vertex not in visited:
			visited.add(vertex)
			queue.extend(graph[vertex] - visited)
	return visited

def bfs(graph, start, goal):
	queue = [(start, [start])]
	while queue:
		(node, path) = queue.pop(0)
		for adj in graph[node] - set(path):
			if adj == goal:
				return path + [adj]
			else:
				queue.append((adj, path + [adj]))
	return []
T = int(input())
for _ in range(T):
	(N, M) = [int(x) for x in input().split()]
	graph = defaultdict(set)
	for _ in range(M):
		(x, y) = [int(x) for x in input().split()]
		graph[x].add(y)
		graph[y].add(x)
	S = int(input())
	nodes_to_reach = list(range(1, N + 1))
	nodes_to_reach.remove(S)
	component_set = component(graph, S)
	res = []
	for n in nodes_to_reach:
		if not graph[S]:
			res.append(-1)
		elif not graph[n]:
			res.append(-1)
		elif n in component_set:
			path = list(bfs(graph, S, n))
			if not path:
				res.append(-1)
			else:
				res.append((len(path) - 1) * 6)
		else:
			res.append(-1)
	print_seq(res)


import queue
trials = int(input())

class Graph:

	def __init__(self, numNodes, numEdges):
		self.numNodes = numNodes
		self.numEdges = numEdges
		self.node = {}

	def addNode(self, node):
		n = Node(node)
		self.node[node] = n

	def addUEdge(self, node1, node2):
		self.node[node1].addEdge(self.node[node2])
		self.node[node2].addEdge(self.node[node1])

	def BFS(self, node):
		for key in range(1, len(self.node) + 1):
			self.node[key].reset()
		self.node[node].color = 1
		self.node[node].distance = 0
		queue = []
		queue.append(node)
		while len(queue) > 0:
			u = queue[0]
			queue = queue[1:]
			for adjNode in self.node[u].adj:
				if self.node[adjNode].distance == -1:
					self.node[adjNode].distance = self.node[u].distance + 1
					queue.append(adjNode)
		out = []
		for key in self.node:
			d = self.node[key].distance
			if d != 0:
				if d == -1:
					out.append(-1)
				else:
					out.append(d * 6)
		output = ''
		for i in range(0, len(out)):
			output += str(out[i])
			if i < len(out) - 1:
				output += ' '
		print(output)

class Node:

	def __init__(self, name):
		self.adj = []
		self.color = 0
		self.name = name
		self.distance = -1

	def addEdge(self, node):
		self.adj.append(node.name)

	def reset(self):
		self.color = 0
		self.distance = -1
while trials > 0:
	trials -= 1
	(nodes, edges) = map(int, input().split(' '))
	G = Graph(nodes, edges)
	for i in range(0, nodes):
		G.addNode(i + 1)
	for i in range(0, edges):
		(x, y) = map(int, input().split(' '))
		G.addUEdge(x, y)
	G.BFS(int(input()))


def main():
	test = int(input())
	while test > 0:
		shortestbfs()
		test -= 1

def shortestbfs():
	(n, m) = list(map(int, input().split()))
	graph = [[0 for i in range(n)] for x in range(n)]
	for i in range(m):
		(x, y) = list(map(lambda x: int(x) - 1, input().split()))
		graph[x][y] = graph[y][x] = 1
	start = int(input()) - 1
	bfs(graph, n, start)

def bfs(graph, n, start):
	visited = [False for i in range(n)]
	visited[start] = True
	queue = [start]
	path = [-1 for i in range(n)]
	path[start] = 0
	while queue != []:
		v = queue.pop(0)
		for i in [adj for (adj, e) in enumerate(graph[v]) if e == 1]:
			if visited[i]:
				continue
			visited[i] = True
			queue += [i]
			path[i] = path[v] + 6
	print(' '.join(map(str, [x for (i, x) in enumerate(path) if i != start])))
main()


from collections import deque

def find_shortest(g, s):
	expansion = deque([(s, 0)])
	expanded = dict()
	while len(expansion) > 0:
		(node, path_length) = expansion.popleft()
		if node in expanded:
			continue
		expanded[node] = path_length
		for j in g[node]:
			if j not in expanded:
				expansion.append((j, path_length + 6))
	return (expanded[i] if i in expanded else -1 for i in range(1, len(g) + 1) if i != s)
for k in range(int(input())):
	(nodes, edges) = (int(x) for x in input().split())
	graph = {i: [] for i in range(1, nodes + 1)}
	for n in range(edges):
		(i, j) = (int(x) for x in input().split())
		graph[i].append(j)
		graph[j].append(i)
	start = int(input())
	print(*find_shortest(graph, start))


from heapq import *

def test_graph(l, g, s):
	dist = [-1] * l
	(q, seen) = ([(0, s)], set())
	while q:
		(cost, v1) = heappop(q)
		if v1 not in seen:
			seen.add(v1)
			dist[v1] = cost
			for x in g[v1]:
				if x not in seen:
					heappush(q, (cost + 6, x))
	print(' '.join([str(dist[x]) for x in range(l) if x != s]))
t = int(input())
for x in range(t):
	(V, E) = map(int, input().split())
	graph = [[] for i in range(V)]
	for y in range(E):
		(n1, n2) = map(int, input().split())
		graph[n1 - 1].append(n2 - 1)
		graph[n2 - 1].append(n1 - 1)
	s = int(input())
	test_graph(V, graph, s - 1)


from collections import OrderedDict
from collections import defaultdict
import asyncio

class Graph:

	def __init__(self):
		self.neighbors = defaultdict(set)
		self.vertices = list()

	def add_edge(self, start, end):
		self.neighbors[start].add(end)
		self.neighbors[end].add(start)

def dijkstra(graph, start):
	infinity = object()
	distances = OrderedDict()
	for vertex in graph.vertices:
		distances[vertex] = infinity
	distances[start] = 0
	trampoline = list()

	def compute(current):
		for neighbor in graph.neighbors[current]:
			new = distances[current] + 6
			if distances[neighbor] is infinity or distances[neighbor] > new:
				distances[neighbor] = new
				trampoline.append(neighbor)
	trampoline.append(start)
	while trampoline:
		vertex = trampoline.pop(0)
		compute(vertex)
	distances = list(distances.values())
	distances.pop(start - 1)
	return map(lambda x: -1 if x is infinity else x, distances)
T = int(input())
for _ in range(T):
	graph = Graph()
	(N, M) = map(int, input().split())
	for name in range(1, N + 1):
		graph.vertices.append(name)
	for _ in range(M):
		(start, end) = map(int, input().split())
		graph.add_edge(start, end)
	S = int(input())
	print(' '.join(map(str, dijkstra(graph, S))))


for i in range(int(input())):
	(n, m) = [int(i) for i in input().split(' ')]
	nodes = [[False] * n for i in range(n)]
	for j in range(m):
		(s, e) = [int(k) - 1 for k in input().split(' ')]
		if s < e:
			nodes[s][e] = True
		else:
			nodes[e][s] = True
	_open = [int(input()) - 1]
	ans = [-1] * n
	count = 0
	next_open = []
	while True:
		while _open != []:
			cur = _open[0]
			ans[cur] = count * 6
			for j in range(n):
				if (nodes[cur][j] or nodes[j][cur]) and ans[j] == -1:
					ans[j] = -2
					next_open = next_open + [j]
			_open = _open[1:]
		if next_open == []:
			break
		else:
			count += 1
			_open = next_open
			next_open = []
	ans = filter(lambda x: x != 0, ans)
	print(' '.join([str(i) for i in ans]))


from collections import deque
T = int(input())
for _ in range(T):
	(N, M) = [int(i) for i in input().split()]
	graph = {}
	for i in range(N):
		graph[i + 1] = []
	for _ in range(M):
		(a, b) = [int(i) for i in input().split()]
		graph[a].append(b)
		graph[b].append(a)
	explored = [-1] * (N + 1)
	s = int(input())
	explored[s] = 0
	queue = deque([s])
	while queue:
		s = queue.popleft()
		for i in graph[s]:
			if explored[i] == -1:
				explored[i] = explored[s] + 6
				queue.append(i)
	result = ''
	for i in range(1, N + 1):
		if explored[i] != 0:
			result += str(explored[i])
			if i != N:
				result += str(' ')
	print(result)


import sys

def bfs(g, s):
	distance = {}
	for v in g:
		distance[v] = sys.maxsize
	distance[s] = 0
	q = {s: distance[s]}
	while q:
		u = min(q.items(), key=lambda x: x[1])[0]
		del q[u]
		for v in g[u]:
			if distance[v] > distance[u] + 6:
				distance[v] = distance[u] + 6
				q[v] = distance[v]
	result = []
	for x in range(1, N + 1):
		if x != s and x in distance:
			if distance[x] < sys.maxsize:
				result.append(distance[x])
			else:
				result.append(-1)
	return result
T = int(input())
for i in range(T):
	graph = {}
	(N, M) = [int(x) for x in input().split()]
	for x in range(1, N + 1):
		graph[x] = []
	for _ in range(M):
		(x, y) = [int(x) for x in input().split()]
		graph[x].append(y)
		graph[y].append(x)
	S = int(input())
	print(' '.join((str(x) for x in bfs(graph, S))))


T = int(input())

def foo():
	ne = input().split()
	(N, E) = (int(ne[0]), int(ne[1]))
	nodes = [[] for i in range(N)]
	visited = [0 for i in range(N)]
	dists = [-1 for i in range(N)]
	for i in range(E):
		edge = input().split()
		(e1, e2) = (int(edge[0]), int(edge[1]))
		nodes[e1 - 1].append(e2 - 1)
		nodes[e2 - 1].append(e1 - 1)
	S = int(input())
	Q = [S - 1]
	dists[S - 1] = 0
	while len(Q) > 0:
		node = Q[0]
		visited[node] = 1
		for n in nodes[node]:
			if visited[n] == 1:
				continue
			visited[n] = 1
			dists[n] = dists[node] + 6
			Q.append(n)
		del Q[0]
	del dists[S - 1]
	output = ' '.join((str(d) for d in dists))
	print(output)
for t in range(T):
	foo()


from queue import Queue

def readEdges(edgeNum):
	edges = []
	for _ in range(edgeNum):
		(node1, node2) = [int(node) for node in input().split()]
		edges.append((node1, node2))
	return edges

def buildGraph(edges):
	graph = {}
	for (node1, node2) in edges:
		addUndirectedEdge(graph, node1, node2)
	return graph

def addUndirectedEdge(graph, node1, node2):
	addDirectedEdge(graph, node1, node2)
	addDirectedEdge(graph, node2, node1)

def addDirectedEdge(graph, fromNode, toNode):
	if fromNode in graph:
		graph[fromNode].add(toNode)
	else:
		graph[fromNode] = set([toNode])

def findShortestPath(graph, nodeNum, startNode):
	size = nodeNum + 1
	shortestPath = [-1] * size
	queue = Queue()
	shortestPath[startNode] = 0
	queue.put(startNode)
	while not queue.empty():
		fromNode = queue.get()
		toNodeArr = graph.get(fromNode)
		if toNodeArr is not None:
			for toNode in toNodeArr:
				if shortestPath[toNode] == -1:
					shortestPath[toNode] = shortestPath[fromNode] + 6
					queue.put(toNode)
	del shortestPath[startNode]
	return shortestPath[1:]

def printShortestPath(shortestPath):
	print(' '.join(map(str, shortestPath)))
n = int(input())
for _ in range(n):
	(nodeNum, edgeNum) = [int(num) for num in input().split()]
	edges = readEdges(edgeNum)
	startNode = int(input())
	graph = buildGraph(edges)
	shortestPath = findShortestPath(graph, nodeNum, startNode)
	printShortestPath(shortestPath)


T = int(input())
for t in range(T):
	(N, M) = [int(x) for x in input().split()]
	graph = {}
	for i in range(1, N + 1):
		graph[str(i)] = []
	for m in range(M):
		(a, b) = input().split()
		graph[a].append(b)
		graph[b].append(a)
	S = input()
	to_visit = list(zip(graph[S], [6] * len(graph[S])))
	visited = {S: 0}
	while to_visit != []:
		node = to_visit.pop()
		if node[0] in visited:
			continue
		else:
			visited[node[0]] = node[1]
			to_visit[:0] = zip(graph[node[0]], [node[1] + 6] * len(graph[node[0]]))
	for i in range(1, N + 1):
		node = str(i)
		if node == S:
			continue
		elif node in visited:
			print(visited[node], end=' ' if i != N else '\n')
		else:
			print(-1, end=' ' if i != N else '\n')


from collections import deque
t = int(input())
for case in range(t):
	(n, m) = [int(x) for x in input().split()]
	nodes = [set() for x in range(n)]
	for line in range(m):
		(a, b) = [int(x) - 1 for x in input().split()]
		if b not in nodes[a]:
			nodes[a].add(b)
		if a not in nodes[b]:
			nodes[b].add(a)
	s = int(input()) - 1
	dist = {x: -1 for x in range(n)}
	q = deque()
	q.append((s, 0))
	visited = set([s])
	while q:
		(node, d) = q.popleft()
		dist[node] = d
		for adj in nodes[node]:
			if dist[adj] == -1:
				q.append((adj, d + 6))
				dist[adj] = 0
	output = []
	for x in range(0, n):
		if x != s:
			output.append(str(dist[x]))
	print(' '.join(output))


def bfs_paths(graph, start, goal):
	queue = [(start, [start])]
	while queue:
		(v, path) = queue.pop(0)
		for next in graph[v] - set(path):
			if next == goal:
				yield (path + [next])
			else:
				queue.append((next, path + [next]))

def shortest_path(graph, start, goal):
	if len(graph[start]) == 0 or len(graph[goal]) == 0:
		return -1
	try:
		return 6 * (len(next(bfs_paths(graph, start, goal))) - 1)
	except StopIteration:
		return -1
t = int(input())
for tt in range(t):
	ret = []
	(n, m) = map(int, input().split())
	graph = dict(((i, set()) for i in range(1, n + 1)))
	for mm in range(m):
		(s, d) = map(int, input().split())
		graph[s].add(d)
		graph[d].add(s)
	start = int(input())
	for a in list((x for x in range(1, n + 1) if x != start)):
		ret.append(shortest_path(graph, start, a))
	print(' '.join(map(str, ret)))