Skip to content

Commit b1e2c28

Browse files
authored
Merge pull request #28 from dwij2812/depthFirstSearch
Added Depth First Search
2 parents 67434fc + 215f4b4 commit b1e2c28

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Algorithms
3535
* [binary search](https://en.wikipedia.org/wiki/Binary_search_algorithm)
3636
* [linear search](https://en.wikipedia.org/wiki/Linear_search)
3737
* [jump search](https://en.wikipedia.org/wiki/Jump_search)
38+
* [depth first search](https://en.wikipedia.org/wiki/Depth-first_search)
3839
* [breadth-first search](https://en.wikipedia.org/wiki/Breadth-first_search)
3940

4041
#### Collections

searching/depthFirstSearch.go

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func getIdx(target int, nodes []int) int {
6+
for i := 0; i < len(nodes); i++ {
7+
if nodes[i] == target {
8+
return i
9+
}
10+
}
11+
return -1
12+
}
13+
14+
func notExist(target int, slice []int) bool {
15+
for i := 0; i < len(slice); i++ {
16+
if slice[i] == target {
17+
return false
18+
}
19+
}
20+
return true
21+
}
22+
23+
func dfs(start, end int, nodes []int, edges [][]bool) ([]int, bool) {
24+
var route []int
25+
var stack []int
26+
startIdx := getIdx(start, nodes)
27+
stack = append(stack, startIdx)
28+
for len(stack) > 0 {
29+
now := stack[len(stack)-1]
30+
route = append(route, nodes[now])
31+
if len(stack) > 1 {
32+
stack = stack[:len(stack)-1]
33+
} else {
34+
stack = stack[:len(stack)-1]
35+
}
36+
for i := 0; i < len(edges[now]); i++ {
37+
if edges[now][i] && notExist(i, stack) {
38+
stack = append(stack, i)
39+
}
40+
edges[now][i] = false
41+
edges[i][now] = false
42+
}
43+
if route[len(route)-1] == end {
44+
return route, true
45+
}
46+
}
47+
return nil, false
48+
}
49+
50+
func main() {
51+
nodes := []int{
52+
1, 2, 3, 4, 5, 6,
53+
}
54+
/*
55+
sample graph
56+
①-②
57+
| |
58+
③-④-⑤-⑥
59+
*/
60+
edges := [][]bool{
61+
{false, true, true, false, false, false},
62+
{true, false, false, true, false, false},
63+
{true, false, false, true, false, false},
64+
{false, true, true, false, true, false},
65+
{false, false, false, true, false, true},
66+
{false, false, false, false, true, false},
67+
}
68+
start := 1
69+
end := 6
70+
route, _ := dfs(start, end, nodes, edges)
71+
fmt.Println(route)
72+
}

0 commit comments

Comments
 (0)