Skip to content

Instantly share code, notes, and snippets.

@pengx17
Last active December 12, 2021 14:55
Show Gist options
  • Select an option

  • Save pengx17/b7c4a5f87559d9f40654c86fb629fa83 to your computer and use it in GitHub Desktop.

Select an option

Save pengx17/b7c4a5f87559d9f40654c86fb629fa83 to your computer and use it in GitHub Desktop.
let input = `fs-end
he-DX
fs-he
start-DX
pj-DX
end-zg
zg-sl
zg-pj
pj-he
RW-he
fs-DX
pj-RW
zg-RW
start-pj
he-WI
zg-he
pj-fs
start-RW`;
function isSmall(str) {
return str.toLowerCase() === str;
}
function run() {
const lines = input.split("\n").filter(Boolean);
/**
* @type {Record<string, string[]>}
*/
const fromTo = lines
.flatMap((line) => {
const [from, to] = line.split("-");
return [
[from, to],
[to, from],
];
})
.filter(([from, to]) => to !== "start")
.reduce((acc, [from, to]) => {
acc[from] = acc[from] || [];
acc[from].push(to);
return acc;
}, {});
function toEnd(next = "start", visited = new Set(), twiceFlag = false) {
if (isSmall(next) && visited.has(next) && twiceFlag) {
return [];
}
if (next === "end") {
return [["end"]];
}
if (isSmall(next)) {
visited = new Set(visited);
if (visited.has(next)) {
twiceFlag = true;
} else {
visited.add(next);
}
}
return fromTo[next]
.flatMap((to) => toEnd(to, visited, twiceFlag))
.map((subPath) => [next, ...subPath]);
}
const res = toEnd().map((line) => line.join(" - "));
console.log(res, res.length);
}
run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment