using System;
using System.Collections.Generic;
class Program {
static void Main(string[] args)
{
List<List<int> > graph = new List<List<int> >();
graph.Add(new List<int>(new int[] { 1, 2, 3 }));
graph.Add(new List<int>(new int[] { 2, 0 }));
graph.Add(new List<int>(new int[] { 0, 1 }));
graph.Add(new List<int>(new int[] { 0, 4 }));
graph.Add(new List<int>(new int[] { 3 }));
int minTime = minimizeTime(graph);
Console.WriteLine(minTime);
}
public static int minimizeTime(List<List<int> > graph)
{
int n = graph.Count;
List<List<int> > adj = new List<List<int> >(n);
for (int i = 0; i < n; i++) {
adj.Add(new List<int>());
foreach(int j in graph[i]) { adj[i].Add(j); }
}
int finalMask = (1 << n) - 1;
Queue<Pair> q = new Queue<Pair>();
bool[, ] visited = new bool[n, finalMask + 1];
for (int i = 0; i < n; i++) {
q.Enqueue(new Pair(i, (1 << i)));
}
int timeCount = 0;
while (q.Count > 0) {
int size = q.Count;
for (int i = 0; i < size; i++) {
Pair curr = q.Dequeue();
if (curr.getValue() == finalMask)
return timeCount;
foreach(int child in adj[curr.getKey()])
{
int newVisitedBit
= curr.getValue() | (1 << child);
if (visited[child, newVisitedBit]
== false) {
q.Enqueue(
new Pair(child, newVisitedBit));
visited[child, newVisitedBit]
= true;
}
}
}
timeCount++;
}
return -1;
}
}
class Pair {
public int first, second;
public Pair(int first, int second)
{
this.first = first;
this.second = second;
}
public int getKey() { return this.first; }
public int getValue() { return this.second; }
}