Created
April 23, 2022 19:12
-
-
Save SuperOleg39/a76041cdeebf9dfc791f14525dd1e7ba 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
| class Node { | |
| constructor(value) { | |
| this.value = value; | |
| this.siblings = new Set(); | |
| } | |
| connect(node) { | |
| if (!node) { | |
| return; | |
| } | |
| this.siblings.add(node) | |
| } | |
| find(value, currentPath = new Set([this])) { | |
| let paths = [] | |
| this.siblings | |
| .forEach((node) => { | |
| const path = new Set(currentPath) | |
| if (path.has(node)) { | |
| return; | |
| } | |
| console.log(Array(path.size).join(' '), 'value', node.value) | |
| path.add(node) | |
| if (node.value === value) { | |
| paths.push(path) | |
| return; | |
| } | |
| paths = [...paths, ...node.find(value, new Set(path))] | |
| }) | |
| return paths; | |
| } | |
| } | |
| const str = '123456789' | |
| const matrix = [] | |
| const nodes = [] | |
| let current = 0 | |
| for (let i = 0; i < 3; i++) { | |
| matrix[i] = [] | |
| nodes[i] = [] | |
| for (let k = 0; k < 3; k++) { | |
| matrix[i][k] = str[current] | |
| nodes[i][k] = new Node(str[current]) | |
| current++ | |
| } | |
| } | |
| for (let i = 0; i < 3; i++) { | |
| for (let k = 0; k < 3; k++) { | |
| const node = nodes[i][k] | |
| node.connect(nodes[i - 1]?.[k]) | |
| node.connect(nodes[i - 1]?.[k - 1]) | |
| node.connect(nodes[i]?.[k - 1]) | |
| node.connect(nodes[i + 1]?.[k]) | |
| node.connect(nodes[i + 1]?.[k + 1]) | |
| node.connect(nodes[i]?.[k + 1]) | |
| node.connect(nodes[i + 1]?.[k - 1]) | |
| node.connect(nodes[i - 1]?.[k + 1]) | |
| } | |
| } | |
| console.log(matrix) | |
| console.log(nodes[0][0].find('9').sort((a, b) => { | |
| return a.size - b.size | |
| })) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment