using
System;
using
System.Collections.Generic;
using
System.Linq;
namespace
GFG {
public
class
GFG {
class
pair {
public
string
first;
public
int
second;
public
pair(
string
first,
int
second)
{
this
.first = first;
this
.second = second;
}
}
static
int
shortestChainLen(
string
start,
string
target,
HashSet<
string
> D)
{
if
(start == target)
return
0;
Dictionary<
string
, List<
string
> > umap
=
new
Dictionary<
string
, List<
string
> >();
for
(
int
i = 0; i < start.Length; i++) {
string
str = start.Substring(0, i) +
"*"
+ start.Substring(i + 1);
if
(!umap.ContainsKey(str))
umap[str] =
new
List<
string
>();
umap[str].Add(start);
}
foreach
(
string
it
in
D)
{
string
word = it;
for
(
int
j = 0; j < word.Length; j++) {
string
str = word.Substring(0, j) +
"*"
+ word.Substring(j + 1);
if
(!umap.ContainsKey(str))
umap[str] =
new
List<
string
>();
umap[str].Add(word);
}
}
Queue<pair> q =
new
Queue<pair>();
Dictionary<
string
,
int
> visited
=
new
Dictionary<
string
,
int
>();
q.Enqueue(
new
pair(start, 1));
visited[start] = 1;
while
(q.Count != 0) {
pair p = q.Peek();
q.Dequeue();
string
word = p.first;
int
dist = p.second;
if
(word == target) {
return
dist;
}
for
(
int
i = 0; i < word.Length; i++) {
string
str = word.Substring(0, i) +
"*"
+ word.Substring(i + 1);
List<
string
> vect
= umap.ContainsKey(str)
? umap[str]
:
new
List<
string
>();
foreach
(
string
s
in
vect)
{
if
(!visited.ContainsKey(s)) {
visited[s] = 1;
q.Enqueue(
new
pair(s, dist + 1));
}
}
}
}
return
0;
}
public
static
void
Main(
string
[] args)
{
HashSet<
string
> D =
new
HashSet<
string
>() {
"poon"
,
"plee"
,
"same"
,
"poie"
,
"plie"
,
"poin"
,
"plea"
};
string
start =
"toon"
;
string
target =
"plea"
;
Console.WriteLine(
"Length of shortest chain is: "
+ shortestChainLen(start, target, D));
}
}
}