1. 程式人生 > >廣度優先演算法走出迷宮

廣度優先演算法走出迷宮

廣度優先演算法(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},{0, -1},{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/maze.in")
    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()
    }
}