8000 新增邻接矩阵 · mohuishou/go-algorithm@8a5b873 · GitHub
[go: up one dir, main page]

8000
Skip to content

Commit 8a5b873

Browse files
committed
新增邻接矩阵
1 parent d6fef80 commit 8a5b873

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

GraphMatrix/GraphMatrix.go

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
//Package GraphMatrix 邻接矩阵表示图
2+
package GraphMatrix
3+
4+
import (
5+
"bufio"
6+
"io"
7+
"os"
8+
"strconv"
9+
"strings"
10+
)
11+
12+
// EdgeType 边的权值类型
13+
type EdgeType int
14+
15+
//Graph 图
16+
type Graph struct {
17+
VNum, ENum int //顶点、边的个数
18+
G [][]EdgeType //邻接矩阵
19+
}
20+
21+
//CreateGraph 创建一个图并且初始化邻接矩阵
22+
func CreateGraph(n int) (graph Graph) {
23+
graph = Graph{VNum: n}
24+
graph.G = make([][]EdgeType, n)
25+
for i := 0; i < n; i++ {
26+
graph.G[i] = make([]EdgeType, n)
27+
}
28+
return graph
29+
}
30+
31+
//BuildGraph 创建图
32+
func BuildGraph(path string) (graph Graph) {
33+
f, err := os.Open(path)
34+
if err != nil {
35+
panic(err)
36+
}
37+
buf := bufio.NewReader(f)
38+
39+
i := 0
40+
//边的数目
41+
for {
42+
line, err := buf.ReadString('\n')
43+
if err != nil {
44+
if err == io.EOF {
45+
return graph
46+
}
47+
panic(err)
48+
}
49+
line = strings.TrimSpace(line)
50+
data := strings.Split(line, " ")
51+
if i == 0 {
52+
n, err := strconv.Atoi(data[0])
53+
if err != nil {
54+
panic(err)
55+
}
56+
graph = CreateGraph(n)
57+
58+
graph.ENum, err = strconv.Atoi(data[1])
59+
if err != nil {
60+
panic(err)
61+
}
62+
} else if i <= graph.ENum {
63+
s, err := strconv.Atoi(data[0])
64+
if err != nil {
65+
panic(err)
66+
}
67+
t, err := strconv.Atoi(data[1])
68+
if err != nil {
69+
panic(err)
70+
}
71+
weight, err := strconv.Atoi(data[2])
72+
if err != nil {
73+
panic(err)
74+
}
75+
graph.G[s][t] = EdgeType(weight)
76+
}
77+
i++
78+
}
79+
80+
}

0 commit comments

Comments
 (0)
0