@@ -605,6 +605,125 @@ if __name__ == "__main__":
605605```
606606### Go
607607
608+ #### 邻接矩阵写法
609+ ``` go
610+ package main
611+
612+ import (
613+ " fmt"
614+ )
615+
616+ var result [][]int // 收集符合条件的路径
617+ var path []int // 1节点到终点的路径
618+
619+ func dfs (graph [][]int , x , n int ) {
620+ // 当前遍历的节点x 到达节点n
621+ if x == n { // 找到符合条件的一条路径
622+ temp := make ([]int , len (path))
623+ copy (temp, path)
624+ result = append (result, temp)
625+ return
626+ }
627+ for i := 1 ; i <= n; i++ { // 遍历节点x链接的所有节点
628+ if graph[x][i] == 1 { // 找到 x链接的节点
629+ path = append (path, i) // 遍历到的节点加入到路径中来
630+ dfs (graph, i, n) // 进入下一层递归
631+ path = path[:len (path)-1 ] // 回溯,撤销本节点
632+ }
633+ }
634+ }
635+
636+ func main () {
637+ var n , m int
638+ fmt.Scanf (" %d %d " , &n, &m)
639+
640+ // 节点编号从1到n,所以申请 n+1 这么大的数组
641+ graph := make ([][]int , n+1 )
642+ for i := range graph {
643+ graph[i] = make ([]int , n+1 )
644+ }
645+
646+ for i := 0 ; i < m; i++ {
647+ var s , t int
648+ fmt.Scanf (" %d %d " , &s, &t)
649+ // 使用邻接矩阵表示无向图,1 表示 s 与 t 是相连的
650+ graph[s][t] = 1
651+ }
652+
653+ path = append (path, 1 ) // 无论什么路径已经是从1节点出发
654+ dfs (graph, 1 , n) // 开始遍历
655+
656+ // 输出结果
657+ if len (result) == 0 {
658+ fmt.Println (-1 )
659+ } else {
660+ for _ , pa := range result {
661+ for i := 0 ; i < len (pa)-1 ; i++ {
662+ fmt.Print (pa[i], " " )
663+ }
664+ fmt.Println (pa[len (pa)-1 ])
665+ }
666+ }
667+ }
668+ ```
669+
670+ #### 邻接表写法
671+ ``` go
672+ package main
673+
674+ import (
675+ " fmt"
676+ )
677+
678+ var result [][]int
679+ var path []int
680+
681+ func dfs (graph [][]int , x , n int ) {
682+ if x == n {
683+ temp := make ([]int , len (path))
684+ copy (temp, path)
685+ result = append (result, temp)
686+ return
687+ }
688+ for _ , i := range graph[x] {
689+ path = append (path, i)
690+ dfs (graph, i, n)
691+ path = path[:len (path)-1 ]
692+ }
693+ }
694+
695+ func main () {
696+ var n , m int
697+ fmt.Scanf (" %d %d " , &n, &m)
698+
699+ graph := make ([][]int , n+1 )
700+ for i := 0 ; i <= n; i++ {
701+ graph[i] = make ([]int , 0 )
702+ }
703+
704+ for m > 0 {
705+ var s , t int
706+ fmt.Scanf (" %d %d " , &s, &t)
707+ graph[s] = append (graph[s], t)
708+ m--
709+ }
710+
711+ path = append (path, 1 )
712+ dfs (graph, 1 , n)
713+
714+ if len (result) == 0 {
715+ fmt.Println (-1 )
716+ } else {
717+ for _ , pa := range result {
718+ for i := 0 ; i < len (pa)-1 ; i++ {
719+ fmt.Print (pa[i], " " )
720+ }
721+ fmt.Println (pa[len (pa)-1 ])
722+ }
723+ }
724+ }
725+ ```
726+
608727### Rust
609728
610729### Javascript
0 commit comments