Skip to content

Commit e1bb82c

Browse files
committed
short_path
1 parent b36f258 commit e1bb82c

File tree

4 files changed

+63
-2
lines changed

4 files changed

+63
-2
lines changed

Makefile

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ fmt :
1010
@gofmt -l -w ./
1111

1212

13+
1314
.PHONY : test
1415
test :
1516
@echo "测试代码"
16-
go test -v ./...
17+
@go test -v ./...

algorithms/graphs/README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,14 @@
1616

1717
思想: 从顶点V出发,访问V之后依次访问v的各个未曾访问过的邻接点,然后分别从这些邻接点出发依次访问它们的邻接点
1818

19-
队列
19+
队列
20+
21+
### 最短路径
22+
23+
#### 迪杰斯特拉(Dijkstra)
24+
25+
[详解01](http://data.biancheng.net/view/46.html)
26+
27+
[详解02](http://www.cnblogs.com/skywang12345/p/3711512.html)
28+
29+
用于有向网中计算一个节点到其他节点的最短路径
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package bfs_shortest_path
2+
3+
import (
4+
"github.com/xiaomeng79/go-algorithm/algorithms/graphs/bfs"
5+
"github.com/xiaomeng79/go-algorithm/data-structures/graph"
6+
)
7+
8+
func ShortestPath(g *graph.DirGraph, start graph.VertexId) (dist map[graph.VertexId]int) {
9+
dist = make(map[graph.VertexId]int)
10+
visited := make(map[graph.VertexId]bool)
11+
12+
getDist := func(v graph.VertexId) { //目标顶点
13+
neighbours := g.GetNeighbours(v).VerticesIter()
14+
visited[v] = true
15+
16+
for neighbour := range neighbours {
17+
18+
ok, _ := visited[neighbour]
19+
if !ok {
20+
dist[neighbour] = dist[v] + 1
21+
}
22+
}
23+
}
24+
bfs.Bfs(g, start, getDist)
25+
return
26+
}
27+
28+
func GetDist(g *graph.DirGraph, from, to graph.VertexId) int {
29+
return ShortestPath(g, from)[to]
30+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package bfs_shortest_path
2+
3+
import (
4+
"github.com/stretchr/testify/assert"
5+
"github.com/xiaomeng79/go-algorithm/data-structures/graph"
6+
"testing"
7+
)
8+
9+
func TestShortestPath(t *testing.T) {
10+
h := graph.NewDirected()
11+
for i := 0; i < 10; i++ {
12+
h.AddVertex(graph.VertexId(i))
13+
}
14+
15+
for i := 0; i < 9; i++ {
16+
h.AddEdge(graph.VertexId(i), graph.VertexId(i+1), 1)
17+
}
18+
19+
assert.Equal(t, 9, GetDist(h, graph.VertexId(0), graph.VertexId(9)))
20+
}

0 commit comments

Comments
 (0)