文章目录
有向有环图的全路径搜索(DFS)
路径图
输出结果(从0到5)
思路
-
根据图生成对应的矩阵
生成一个6*6的二维数组,数组的arr[i][j]
数组表示从 i 到 j ,0 表示无法到达,1表示到达,如果有权在,这里可以不用1,用权重数字。 -
找出每一个点可以进入的邻居节点,得到一个新的数组
-
根据DFS找出到达目标点的路径。(参考https://blog.csdn.net/dfsgwe1231/article/details/105997539)
代码
var data=[
[0,1,0,1,1,1],
[1,0,1,0,1,0],
[0,0,0,1,0,1],
[0,0,1,0,1,0],
[1,0,0,0,0,1],
[1,0,0,0,1,0]];
var neighbor={};
for (var i = 0; i < data.length; i++) {
for (var j = 0; j< data[i].length; j++) {
if(data[i][j]!=0){
neighbor[i]=neighbor[i]||[];
neighbor[i].push(j);
}
}
}
console.log(neighbor);
function dfs2(current,path,rs,target){
if(current==target){
console.warn(rs);
}
else
{
let vNeighbor = neighbor[current];
for(let i=0;i<vNeighbor.length;i++){
let next = vNeighbor[i];
let tpath = [].concat(path);
let trs = rs;
if(path.indexOf(next)==-1){
let ptrs =( trs+=`-->${next}`);
tpath.push(next);
let ptpath =[].concat(tpath);
dfs2(next,ptpath,ptrs,target);
}
}
}
}
dfs2(0,[0],"0",5);
https://blog.csdn.net/dfsgwe1231/article/details/105997539
https://blog.csdn.net/qq1263292336/article/details/50193885
https://zhuanlan.zhihu.com/p/54510444