let CHARS = 26;
class Graph {
constructor(V) {
this.V = V;
this.adj = Array.from(Array(V), () => new Array());
this.in = new Array(V);
for (let i = 0; i < V; i++) {
this.in[i] = 0;
}
}
addEdge(v, w) {
this.adj[v].push(w);
this.in[w]++;
}
isEulerianCycle() {
if (this.isSC() == false) return false;
for (let i = 0; i < this.V; i++)
if (this.adj[i].length != this.in[i]) return false;
return true;
}
isSC() {
let visited = new Array(this.V);
for (let i = 0; i < this.V; i++) visited[i] = false;
let n;
for (n = 0; n < this.V; n++) if (this.adj[n].length > 0) break;
this.DFSUtil(n, visited);
for (let i = 0; i < this.V; i++)
if (this.adj[i].length > 0 && visited[i] == false) return false;
let gr = this.getTranspose();
for (let i = 0; i < this.V; i++) visited[i] = false;
gr.DFSUtil(n, visited);
for (let i = 0; i < this.V; i++)
if (this.adj[i].length > 0 && visited[i] == false) return false;
return true;
}
DFSUtil(v, visited) {
visited[v] = true;
for (let j in this.adj[v]) {
let i = this.adj[v][j];
if (!visited[i]) {
this.DFSUtil(i, visited);
}
}
}
getTranspose() {
let g = new Graph(this.V);
for (let v = 0; v < this.V; v++) {
for (let j in this.adj[v]) {
let i = this.adj[v][j];
g.adj[i].push(v);
g.in[v]++;
}
}
return g;
}
}
function canBeChained(arr, n) {
let g = new Graph(CHARS);
for (let i = 0; i < n; i++) {
let s = arr[i];
g.addEdge(
s[0].charCodeAt() - "a".charCodeAt(),
s[s.length - 1].charCodeAt() - "a".charCodeAt()
);
}
return g.isEulerianCycle();
}
let arr1 = ["for", "geek", "rig", "kaf"];
let n1 = arr1.length;
canBeChained(arr1, n1)
? console.log("Can be chained")
: console.log("Can't be chained");
let arr2 = ["aab", "abb"];
let n2 = arr2.length;
canBeChained(arr2, n2)
? console.log("Can be chained")
: console.log("Can't be chained");