henryspace

记录精彩的程序人生 开始使用

Part 25 - Go 语言学习 - 广度优先算法走迷宫

广度优先算法

  1. 迷宫数据

    设有一个6行5列的迷宫,从左上角出发到达右下角,只能横向或纵向走,1为墙,0为出路,问如何走出去

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
  1. 代码示例
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)

    // 读出迷宫所在的行,6行5列
	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
}

// 初始位置0,0的四周点位
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/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) //3位对齐
		}
		fmt.Println()
	}

}

结果1->13
0   0   4   5   6 
1   2   3   0   7 
2   0   4   0   8 
0   0   0  10   9 
0   0  12  11   0 
0   0  13  12  13 


评论
留下你的脚步