Path Solving
This commit is contained in:
@@ -89,6 +89,99 @@ func GenerateMaze(width int, height int) [][]int {
|
||||
return matrix
|
||||
}
|
||||
|
||||
func FindSolutionPath(matrix [][]int) [][]bool {
|
||||
height := len(matrix)
|
||||
if height == 0 {
|
||||
return nil
|
||||
}
|
||||
width := len(matrix[0])
|
||||
if width == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
startX := -1
|
||||
endX := -1
|
||||
for x := 0; x < width; x++ {
|
||||
if matrix[0][x] == 1 {
|
||||
startX = x
|
||||
break
|
||||
}
|
||||
}
|
||||
for x := 0; x < width; x++ {
|
||||
if matrix[height-1][x] == 1 {
|
||||
endX = x
|
||||
break
|
||||
}
|
||||
}
|
||||
if startX == -1 || endX == -1 {
|
||||
return nil
|
||||
}
|
||||
|
||||
start := startX
|
||||
end := (height-1)*width + endX
|
||||
parent := make([]int, width*height)
|
||||
for i := range parent {
|
||||
parent[i] = -1
|
||||
}
|
||||
visited := make([]bool, width*height)
|
||||
queue := make([]int, 1, width*height)
|
||||
queue[0] = start
|
||||
visited[start] = true
|
||||
|
||||
dx := [4]int{0, 1, 0, -1}
|
||||
dy := [4]int{-1, 0, 1, 0}
|
||||
|
||||
found := false
|
||||
for head := 0; head < len(queue); head++ {
|
||||
idx := queue[head]
|
||||
if idx == end {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
|
||||
x := idx % width
|
||||
y := idx / width
|
||||
for i := 0; i < 4; i++ {
|
||||
nx := x + dx[i]
|
||||
ny := y + dy[i]
|
||||
if nx < 0 || nx >= width || ny < 0 || ny >= height {
|
||||
continue
|
||||
}
|
||||
if matrix[ny][nx] == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
nIdx := ny*width + nx
|
||||
if visited[nIdx] {
|
||||
continue
|
||||
}
|
||||
visited[nIdx] = true
|
||||
parent[nIdx] = idx
|
||||
queue = append(queue, nIdx)
|
||||
}
|
||||
}
|
||||
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
|
||||
pathCells := make([]bool, width*height)
|
||||
for idx := end; idx != -1; idx = parent[idx] {
|
||||
pathCells[idx] = true
|
||||
if idx == start {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
path := make([][]bool, height)
|
||||
for y := 0; y < height; y++ {
|
||||
rowStart := y * width
|
||||
path[y] = pathCells[rowStart : rowStart+width]
|
||||
}
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
func shuffledDirections() [4]uint8 {
|
||||
dirs := [4]uint8{0, 1, 2, 3}
|
||||
for i := 3; i > 0; i-- {
|
||||
|
||||
Reference in New Issue
Block a user