package main
import (
"fmt"
)
// 定义坐标结构
type Coordinate struct {
x, y int
}
// 定义地图大小
const (
rows = 4
cols = 4
)
// 定义地图数组
var grid = [][]int{
{0, 1, 1, 0},
{0, 1, 0, 0},
{0, 0, 0, 0},
{0, 1, 1, 0},
}
// 定义四个移动方向(上、下、左、右)
var directions = []Coordinate{
{-1, 0}, // 上
{1, 0}, // 下
{0, -1}, // 左
{0, 1}, // 右
}
// 广度优先搜索算法
func BFS(start, target Coordinate) []Coordinate {
//已经走过的
visited := make([][]bool, rows)
for i := range visited {
visited[i] = make([]bool, cols)
}
//定义路线
queue := [][]Coordinate{{start}}
//起点定义已经走过
visited[start.x][start.y] = true
for len(queue) > 0 {
path := queue[0]
queue = queue[1:]
node := path[len(path)-1]
if node == target {
return path
}
for _, dir := range directions {
newX, newY := node.x+dir.x, node.y+dir.y
// 检查移动是否越界
if newX < 0 || newX >= rows || newY < 0 || newY >= cols {
continue
}
// 检查移动是否遇到障碍物或已访问过的位置
if grid[newX][newY] == 1 || visited[newX][newY] {
continue
}
// 将新的位置加入路径中
newPath := make([]Coordinate, len(path)+1)
copy(newPath, path)
newPath[len(newPath)-1] = Coordinate{newX, newY}
queue = append(queue, newPath)
visited[newX][newY] = true
}
}
return nil
}
func main() {
start := Coordinate{0, 0}
target := Coordinate{2, 1}
path := BFS(start, target)
if path != nil {
fmt.Printf("从起点(%d,%d)到终点(%d,%d)的最短路径为:\n", start.x, start.y, target.x, target.y)
for _, node := range path {
fmt.Printf("(%d, %d) ", node.x, node.y)
}
fmt.Println()
} else {
fmt.Printf("无法从起点(%d,%d)到达终点(%d,%d)!\n", start.x, start.y, target.x, target.y)
}
}