Skip to content

Instantly share code, notes, and snippets.

@ironmancaijian
Created June 10, 2020 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ironmancaijian/fe60d1edf9d11d8b5a0288aaafe4e5bc to your computer and use it in GitHub Desktop.
Save ironmancaijian/fe60d1edf9d11d8b5a0288aaafe4e5bc to your computer and use it in GitHub Desktop.
const data = [{
from:'a',to: 'e'
},{
from:'b',to: 'c'
},{
from:'b',to: 'h'
},{
from:'b',to: 'x'
},{
from: 'c',to: 'e'
},{
from: 'd',to: 'e'
},{
from: 'a',to: 'd'
},{
from: 'a',to: 'h'
},{
from: 'h',to: 'd'
}]
// 路径寻找,从data 数据中, 找到所有起始点root 到 目标target点的路径
// a -> e 结果[[a,e],[a,b,c,e],[a,d,e],[a,h,d,e]]
function findPath(data, root, target) {
let res = []
let childRes = [];
(function dsf(data, root, target, res, childRes) {
childRes.push(root)
const nextPath = data.filter(d => {
if (d.from == root) {
d.isVisit = true
}
return d.from == root
}).map(item => item.to)
if (!nextPath.length) {
childRes.pop()
return
}
const nextData = data.filter(d => !d.isVisit)
for (let i = 0; i < nextPath.length; i++) {
let to = nextPath[i]
if (to == target) {
childRes.push(to)
res.push(JSON.parse(JSON.stringify(childRes)))
childRes.pop()
} else {
dsf(nextData, to, target, res, childRes)
}
}
})(data, root, target, res, childRes)
return res
}
console.log(findPath(data, 'a', 'e'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment