xxxxxxxxxx
109
let input = ["cz-end","cz-WR","TD-end","TD-cz","start-UM","end-pz","kb-UM","mj-UM","cz-kb","WR-start","WR-pz","kb-WR","TD-kb","mj-kb","TD-pz","UM-pz","kb-start","pz-mj","WX-cz","sp-WR","mj-WR"];
// input = ["dc-end","HN-start","start-kj","dc-start","dc-HN","LN-dc","HN-end","kj-sa","kj-HN","kj-dc"];
// input = ["start-A","start-b","A-c","A-b","b-d","A-end","b-end"];
function setup() {
createCanvas(1, 1);
solve()
}
function draw() {
background(220);
}
function solve() {
let g = makeGraph(input);
// print(g);
findPaths(g);
}
function findPaths(g) {
let num = 0;
let stack = [['start', {}, false]];
let dup = "dup";
while(stack.length > 0) {
let curr = stack.pop();
let node = curr[0];
let visited = curr[1];
let twice = curr[2];
// print(curr);
if(node == "end") {
num ++;
// print("At end", num);
} else {
if(isLower(node)) {
if(node in visited) {
visited[dup] = node;
} else {
visited[node] = node;
}
}
let children = g[node];
// print(children);
for(let i = 0; i < children.length; i ++) {
let c = children[i];
if(isLower(c) && !twice && c in visited && c != "end" && c != "start") {
let v = d(visited);
v[c] = c;
stack.push([c, v, true]);
}
if(!isLower(c) || (isLower(c) && !(c in visited))) {
if(c != "start") {
v = d(visited);
v[c] = c;
stack.push([c, v, twice]);
}
}
}
}
}
print(num);
print(millis());
}
function d(a) {
return JSON.parse(JSON.stringify(a));
}
function makeGraph() {
let g = {};
for(let i = 0; i < input.length; i ++) {
let caves = input[i].split("-");
let c1 = caves[0];
let c2 = caves[1];
if(!(c1 in g)) {
g[c1] = [];
}
g[c1].push(c2);
if(!(c2 in g)) {
g[c2] = [];
}
g[c2].push(c1);
}
return g;
}
function isLower(s) {
return s.toLowerCase() == s;
}