import java.util.ArrayList;
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
class Pair
{
int first, second;
public Pair(int first, int second)
{
this.first = first;
this.second = second;
}
}
class GFG{
static final int N = 100000 + 1;
static final int inf = 1000000;
static int[] dist = new int[N];
static int[] source = new int[N];
static Deque<Pair> BFSQueue = new LinkedList<>();
static int[] visited = new int[N];
static void BFS(ArrayList<Integer>[] graph, int start)
{
while (!BFSQueue.isEmpty())
BFSQueue.removeLast();
BFSQueue.add(new Pair(start, 0));
while (!BFSQueue.isEmpty())
{
int s = BFSQueue.peekFirst().first;
int d = BFSQueue.peekFirst().second;
visited[s] = 1;
BFSQueue.removeFirst();
if (source[s] == 1)
{
dist[start] = d;
return;
}
for(int i = 0; i < graph[s].size(); i++)
if (visited[graph[s].get(i)] == 0)
BFSQueue.add(new Pair(
graph[s].get(i), d + 1));
}
}
static void nearestTown(ArrayList<Integer>[] graph,
int n, int sources[], int S)
{
for(int i = 1; i <= n; i++)
source[i] = 0;
for(int i = 0; i <= S - 1; i++)
source[sources[i]] = 1;
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= n; j++)
visited[j] = 0;
BFS(graph, i);
}
for(int i = 1; i <= n; i++)
System.out.println(i + " " + dist[i]);
}
static void addEdge(ArrayList<Integer>[] graph,
int u, int v)
{
graph[u].add(v);
graph[v].add(u);
}
public static void main(String[] args)
{
int n = 6;
@SuppressWarnings("unchecked")
ArrayList<Integer>[] graph = new ArrayList[n + 1];
Arrays.fill(graph, new ArrayList<>());
addEdge(graph, 1, 2);
addEdge(graph, 1, 6);
addEdge(graph, 2, 6);
addEdge(graph, 2, 3);
addEdge(graph, 3, 6);
addEdge(graph, 5, 4);
addEdge(graph, 6, 5);
addEdge(graph, 3, 4);
addEdge(graph, 5, 3);
int sources[] = { 1, 5 };
int S = sources.length;
nearestTown(graph, n, sources, S);
}
}