using
System;
using
System.Collections.Generic;
class
Graph {
static
void
LexiBFS(Dictionary<
char
, HashSet<
char
> > G,
char
S, Dictionary<
char
,
bool
> vis)
{
Queue<
char
> q =
new
Queue<
char
>();
q.Enqueue(S);
vis[S] =
true
;
while
(q.Count != 0) {
char
top = q.Peek();
Console.Write(top +
" "
);
if
(G.ContainsKey(top)) {
List<
char
> sortedAdjList
=
new
List<
char
>(G[top]);
sortedAdjList.Sort();
foreach
(
char
i
in
sortedAdjList)
{
if
(vis.ContainsKey(i)) {
if
(!vis[i]) {
vis[i] =
true
;
q.Enqueue(i);
}
}
else
{
vis[i] =
true
;
q.Enqueue(i);
}
}
}
q.Dequeue();
}
}
static
void
CreateGraph(
int
N,
int
M,
char
S,
char
[, ] Edges)
{
Dictionary<
char
, HashSet<
char
> > G
=
new
Dictionary<
char
, HashSet<
char
> >();
for
(
int
i = 0; i < M; i++) {
char
u = Edges[i, 0];
char
v = Edges[i, 1];
if
(G.ContainsKey(u)) {
G[u].Add(v);
}
else
{
HashSet<
char
> temp =
new
HashSet<
char
>();
temp.Add(v);
G[u] = temp;
}
if
(!G.ContainsKey(v)) {
G[v] =
new
HashSet<
char
>();
}
}
Dictionary<
char
,
bool
> vis
=
new
Dictionary<
char
,
bool
>();
LexiBFS(G, S, vis);
}
public
static
void
Main()
{
int
N = 10, M = 10;
char
S =
'a'
;
char
[, ] Edges
= { {
'a'
,
'y'
}, {
'a'
,
'z'
}, {
'a'
,
'p'
},
{
'p'
,
'c'
}, {
'p'
,
'b'
}, {
'y'
,
'm'
},
{
'y'
,
'l'
}, {
'z'
,
'h'
}, {
'z'
,
'g'
},
{
'z'
,
'i'
} };
CreateGraph(N, M, S, Edges);
}
}