Last active
December 12, 2021 14:55
-
-
Save pengx17/b7c4a5f87559d9f40654c86fb629fa83 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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