Skip to content

Instantly share code, notes, and snippets.

@SuperOleg39
Created April 23, 2022 19:12
Show Gist options
  • Select an option

  • Save SuperOleg39/a76041cdeebf9dfc791f14525dd1e7ba to your computer and use it in GitHub Desktop.

Select an option

Save SuperOleg39/a76041cdeebf9dfc791f14525dd1e7ba to your computer and use it in GitHub Desktop.
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