-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.go
113 lines (96 loc) · 2.33 KB
/
graph.go
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
113
package main
import (
"bufio"
"fmt"
"os"
"slices"
"strconv"
"strings"
)
type Node struct {
Name int
Children []*Node
}
type Graph struct {
nodes []*Node
}
func readGraph(filePath string) Graph {
file, ferr := os.Open(filePath)
if ferr != nil {
panic(ferr)
}
scanner := bufio.NewScanner(file)
graph := new(Graph)
for scanner.Scan() {
line := scanner.Text()
nodes := strings.Split(line, " ")
parentNode, errPr := strconv.Atoi(nodes[0])
childNode, errCh := strconv.Atoi(nodes[1])
if errPr != nil {
panic(errPr)
} else if errCh != nil {
panic(errPr)
}
var parentNodeIndex int
var childNodeIndex int
if !GraphContains(graph.nodes, parentNode) {
graph.nodes = append(graph.nodes, new(Node))
parentNodeIndex = len(graph.nodes) - 1
graph.nodes[parentNodeIndex].Name = parentNode
} else {
parentNodeIndex = GraphContainsIndex(graph.nodes, parentNode)
}
if !GraphContains(graph.nodes, childNode) {
graph.nodes = append(graph.nodes, new(Node))
childNodeIndex = len(graph.nodes) - 1
graph.nodes[childNodeIndex].Name = childNode
} else {
childNodeIndex = GraphContainsIndex(graph.nodes, childNode)
}
graph.nodes[parentNodeIndex].Children = append(graph.nodes[parentNodeIndex].Children, graph.nodes[childNodeIndex])
}
return *graph
}
func (graph Graph) findPathLengthDFS(startNode int, finishNode int) int {
startNodeIndex := GraphContainsIndex(graph.nodes, startNode)
startNodePointer := graph.nodes[startNodeIndex]
stack := []*Node{startNodePointer}
depthMap := map[int]int{
startNode: 0,
}
var visitedSlice []int
for len(stack) > 0 {
current := stack[len(stack)-1]
visitedSlice = append(visitedSlice, current.Name)
stack = stack[:len(stack)-1]
fmt.Printf("%d-", current.Name)
for _, child := range current.Children {
if !slices.Contains(visitedSlice, child.Name) {
stack = append(stack, child)
depthMap[child.Name] = depthMap[current.Name] + 1
if child.Name == finishNode {
fmt.Printf("%d", child.Name)
return depthMap[child.Name]
}
}
}
}
fmt.Println(depthMap)
return -1
}
func GraphContains(sl []*Node, v int) bool {
for _, vv := range sl {
if vv.Name == v {
return true
}
}
return false
}
func GraphContainsIndex(sl []*Node, v int) int {
for index, vv := range sl {
if vv.Name == v {
return index
}
}
return -1
}