1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| package Graph
import ( "bufio" "io" "os" "strconv" "strings" )
type EdgeType int
type VextexType int
type VextexDataType int
type EdgeNode struct { Weight EdgeType V VextexType Next *EdgeNode }
type VextexNode struct { data VextexDataType FisrtEdge *EdgeNode }
type Graph struct { VNum, ENum int G []VextexNode }
func CreateGraph(VNum int) (graph Graph) { graph.VNum = VNum graph.G = make([]VextexNode, VNum) for i := 0; i < VNum; i++ { graph.G[i] = VextexNode{} } return graph }
func (graph Graph) AddEdge(s, t VextexType, weight EdgeType) { edge := &EdgeNode{V: t, Weight: weight}
edge.Next = graph.G[s].FisrtEdge graph.G[s].FisrtEdge = edge }
func BuildGraph(path string) (graph Graph) { f, err := os.Open(path) if err != nil { panic(err) } buf := bufio.NewReader(f)
i := 0 for { line, err := buf.ReadString('\n') if err != nil { if err == io.EOF { return graph } panic(err) } line = strings.TrimSpace(line) data := strings.Split(line, " ") if i == 0 { n, err := strconv.Atoi(data[0]) if err != nil { panic(err) } graph = CreateGraph(n)
graph.ENum, err = strconv.Atoi(data[1]) if err != nil { panic(err) } } else if i <= graph.ENum { s, err := strconv.Atoi(data[0]) if err != nil { panic(err) } t, err := strconv.Atoi(data[1]) if err != nil { panic(err) } weight, err := strconv.Atoi(data[2]) if err != nil { panic(err) } graph.AddEdge(VextexType(s), VextexType(t), EdgeType(weight)) } i++ }
}
|