Exemplo n.º 1
0
        public static void Solve()
        {
            var(first, last) = Scanner.Scan <string, string>();
            if (first == last)
            {
                Printer.Print(0);
                Printer.Print(first);
                Printer.Print(last);
                return;
            }
            var N = Scanner.Scan <int>();
            var W = new List <string>();

            W.Add(first);
            for (var i = 0; i < N; i++)
            {
                var w = Scanner.Scan <string>();
                if (w != first && w != last)
                {
                    W.Add(w);
                }
            }
            W.Add(last);
            W = W.Distinct().ToList();
            var G      = new List <int> [W.Count].Select(x => new List <int>()).ToArray();
            var length = first.Length;

            for (var i = 0; i < W.Count - 1; i++)
            {
                for (var j = i + 1; j < W.Count; j++)
                {
                    if (i == j)
                    {
                        G[i][j] = 0; continue;
                    }
                    var count = 0;
                    for (var k = 0; k < length && count < 2; k++)
                    {
                        if (W[i][k] != W[j][k])
                        {
                            count++;
                        }
                    }
                    if (count != 1)
                    {
                        continue;
                    }
                    G[i].Add(j);
                    G[j].Add(i);
                }
            }

            var queue = new Queue <int>();

            queue.Enqueue(0);
            var depths = Enumerable.Repeat(-1, W.Count).ToArray();

            depths[0] = 0;
            var parent = new int[W.Count];

            while (queue.Any())
            {
                var current = queue.Dequeue();
                foreach (var next in G[current])
                {
                    if (depths[next] != -1)
                    {
                        continue;
                    }
                    depths[next] = depths[current] + 1;
                    parent[next] = current;
                    queue.Enqueue(next);
                }
            }

            var answer = depths[^ 1];