File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ * 路径查询
3+ */
4+ module . exports = class Path {
5+ // 构造函数,寻路算法,寻找图graph从s点到其他点的路径
6+ constructor ( g , s ) {
7+ this . data = g . g ; // 获取传入图的数据
8+ this . visited = new Array ( g . V ( ) ) . fill ( false ) ; // 记录节点是否被访问过
9+ if ( s > g . V ( ) ) s = g . V ( ) - 1 ; // 防止越界
10+ this . s = s ; // 起始点
11+ this . from = new Array ( g . V ( ) ) . fill ( - 1 ) ; // 记录路径,from[i]表示查找的路径上i的一个节点
12+
13+ // 寻路算法
14+ this . dfs ( s ) ;
15+ }
16+ // 图的深度优先遍历
17+ dfs ( v ) {
18+ this . visited [ v ] = true ;
19+ for ( let i = 0 ; i < this . data [ v ] . length ; i ++ ) {
20+ if ( ! this . visited [ this . data [ v ] [ i ] ] ) {
21+ this . from [ this . data [ v ] [ i ] ] = v ;
22+ this . dfs ( this . data [ v ] [ i ] ) ;
23+ }
24+ }
25+ }
26+ // 查询从s点到w点是否有路径
27+ hasPath ( w ) {
28+ if ( w < 0 || w > this . data . length ) return false ;
29+ return this . visited [ w ] ;
30+ }
31+ // 查询从s点到w点的路径
32+ path ( w ) {
33+ if ( ! this . hasPath ( w ) ) return ;
34+ var s = [ ] ;
35+ // 通过from数组逆向查找到从s到w的路径,存放到栈中
36+ var p = w ;
37+ while ( p !== - 1 ) {
38+ s . push ( p ) ;
39+ p = this . from [ p ] ;
40+ }
41+ // 交换数组顺序
42+ var res = s . reverse ( ) ;
43+ return res ;
44+ }
45+ // 打印出从s到w点的路径
46+ showPath ( w ) {
47+ if ( ! this . hasPath ( w ) ) return ;
48+ var res = this . path ( w ) ;
49+ var str = "" ;
50+ for ( let i = 0 ; i < res . length ; i ++ ) {
51+ str += res [ i ] ;
52+ if ( i === res . length - 1 ) {
53+ str += "\n" ;
54+ } else {
55+ str += " -> " ;
56+ }
57+ }
58+ console . log ( str ) ;
59+ }
60+ }
Original file line number Diff line number Diff line change @@ -70,4 +70,9 @@ cgraph.addEdge(3, 5);
7070cgraph . addEdge ( 4 , 5 ) ;
7171cgraph . addEdge ( 4 , 6 ) ;
7272var c = new Component ( cgraph ) ;
73- console . log ( "联通分量为: " + c . count ( ) ) ;
73+ console . log ( "联通分量为: " + c . count ( ) ) ;
74+
75+ console . log ( '==============================测试寻路算法==========================================' ) ;
76+ var Path = require ( './Path' ) ;
77+ var p = new Path ( cgraph , 0 ) ;
78+ p . showPath ( 6 ) ;
You can’t perform that action at this time.
0 commit comments