-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathproblem064.go
More file actions
65 lines (58 loc) · 2.1 KB
/
Copy pathproblem064.go
File metadata and controls
65 lines (58 loc) · 2.1 KB
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
package problem064
type coordinates struct {
x int
y int
}
func CountKnightsPaths(boardSize int) int {
totalCountChannel := make(chan int, boardSize*boardSize)
countPaths := func(x int, y int) {
visitedCoordinates := make(map[coordinates]bool)
initialCoordinates := coordinates{x: x, y: y}
visitedCoordinates[initialCoordinates] = true
totalCountChannel <- countPathsByBruteforce(visitedCoordinates, initialCoordinates, boardSize)
}
for initialX := 0; initialX < boardSize; initialX++ {
for initialY := 0; initialY < boardSize; initialY++ {
go countPaths(initialX, initialY)
}
}
totalCount := 0
for i := 0; i < boardSize*boardSize; i++ {
select {
case partialCount := <-totalCountChannel:
totalCount += partialCount
}
}
return totalCount
}
func getAllNextCoordinates(currentCoordinates coordinates) []coordinates {
return []coordinates{
{x: currentCoordinates.x - 2, y: currentCoordinates.y - 1},
{x: currentCoordinates.x - 1, y: currentCoordinates.y - 2},
{x: currentCoordinates.x + 1, y: currentCoordinates.y - 2},
{x: currentCoordinates.x + 2, y: currentCoordinates.y - 1},
{x: currentCoordinates.x + 2, y: currentCoordinates.y + 1},
{x: currentCoordinates.x + 1, y: currentCoordinates.y + 2},
{x: currentCoordinates.x - 1, y: currentCoordinates.y + 2},
{x: currentCoordinates.x - 2, y: currentCoordinates.y + 1},
}
}
func countPathsByBruteforce(visitedCoordinates map[coordinates]bool, currentCoordinates coordinates, boardSize int) int {
if len(visitedCoordinates) == boardSize*boardSize {
return 1
}
pathCount := 0
allNextCoordinates := getAllNextCoordinates(currentCoordinates)
for _, nextCoordinates := range allNextCoordinates {
if nextCoordinates.x >= 0 && nextCoordinates.x <= boardSize-1 &&
nextCoordinates.y >= 0 && nextCoordinates.y <= boardSize-1 &&
!visitedCoordinates[nextCoordinates] {
visitedCoordinates[nextCoordinates] = true
if nextPathCount := countPathsByBruteforce(visitedCoordinates, nextCoordinates, boardSize); nextPathCount > 0 {
pathCount += nextPathCount
}
delete(visitedCoordinates, nextCoordinates)
}
}
return pathCount
}