广度优先算法走出迷宫

2021年9月23日 7点热度 0条评论 来源: weixin_30335575

广度优先算法(Breadth-First Search),同广度优先搜索,又称作宽度优先搜索,或横向优先搜索,简称BFS,是一种图形搜索演算法。简单的说,BFS是从根节点开始,沿着树的宽度遍历树的节点,如果发现目标,则演算终止。广度优先搜索的实现一般采用open-closed表。

有这么一个迷宫:

6 5
0 1 0 0 0
0 0 0 1 0
0 1 0 1 0
1 1 1 0 0
0 1 0 0 1
0 1 0 0 0

其中第一行6代表行数,5代表列表,0代表可以走的路线。1代表墙壁。
假想有一个x轴和y轴, 开始位置: 0,0 终点位置: 6,5
用程序实现最短的路线如下:

package main

import (
    "fmt"
    "os"
)

func readMaze(filename string) [][]int {
    file, err := os.Open(filename)
    if err != nil {
        panic(err)
    }
    var row, col int
    fmt.Fscanf(file, "%d %d", &row, &col)

    maze := make([][]int, row)
    for i := range maze {
        maze[i] = make([]int, col)
        for j := range maze[i] {
            fmt.Fscanf(file, "%d", &maze[i][j])
        }
    }
    return maze
}

type point struct {
    i, j int
}

var dirs = [4]point{
    {-1, 0},{0, -1},{1, 0},{0, 1},
}

func (p point) add(r point) point {
    return point{p.i + r.i, p.j + r.j }
}

func (p point) at(grid [][]int) (int, bool) {
    if p.i < 0 || p.i >= len(grid) {
        return 0, false
    }

    if p.j < 0 || p.j >= len(grid[p.i]) {
        return 0, false
    }

    return grid[p.i][p.j], true
}

func walk(maze [][]int, start, end point) [][]int {
    steps := make([][]int, len(maze))
    for i := range steps {
        steps[i] = make([]int, len(maze[i]))
    }

    Q := []point{start}

    for len(Q) > 0 {
        cur := Q[0]
        Q = Q[1:]

        if cur == end {
            break
        }
        for _, dir := range dirs {
            next := cur.add(dir)

            val, ok := next.at(maze)
            if !ok || val == 1 {
                continue
            }

            val, ok = next.at(steps)
            if !ok || val != 0 {
                continue
            }

            if next == start {
                continue
            }

            curSteps, _ := cur.at(steps)
            steps[next.i][next.j] = curSteps + 1
            Q = append(Q, next)
        }
    }
    return steps
}

func main() {
    maze := readMaze("./maze.in")
    for i := range maze {
        for _, j := range maze[i] {
            fmt.Printf("%3d", j)
        }
        fmt.Println()
    }
    fmt.Println()
    steps := walk(maze, point{0,0},point{len(maze) - 1, len(maze[0]) - 1})

    for _, row := range steps {
        for _, val := range row {
            fmt.Printf("%3d", val)
        }
        fmt.Println()
    }
}

golang数据结构:
https://github.com/Workiva/go-datastructures
https://github.com/emirpasic/gods

转载于:https://www.cnblogs.com/Csir/p/9969396.html

    原文作者:weixin_30335575
    原文地址: https://blog.csdn.net/weixin_30335575/article/details/95518926
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。