# golang学习笔记——迷宫的广度优先搜索

#### 迷宫算法

package main

import (
"fmt"
"os"
)

const (
mazePath = "/home/udi/Udi_work_space/Udi_ws_go/muke/12/1&2/maze.txt"
)

// var res [][]int
open, errOpen := os.Open(path)
if errOpen != nil {
panic(errOpen)
}

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

return maze
}

type point struct {
i, j int
}

var (
dirs = [4]point{
{-1, 0}, //上
{0, -1}, //left
{1, 0},  //down
{0, 1},  //right
}
)

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 walkMaze(maze [][]int, start, end point) ([][]int, []point) {
//创建一个与maze一模一样但是里面value全为0的二元数组
steps := make([][]int, len(maze))
res := []point{}
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 {
//maze at next is 0
//and steps at next is 0
//and next != start
value, ok := next.at(maze)
if !ok || value == 1 {
continue
}
value, ok = next.at(steps)
if !ok || value != 0 {
continue
}
if next == start {
continue
}
curStep, _ := cur.at(steps)
steps[next.i][next.j] = curStep + 1
res = append(res, point{next.i + 1, next.j + 1})
Q = append(Q, next)
}
}

return steps, res
}

func main() {
// for _, row := range res {
// 	for _, val := range row {
// 		fmt.Printf("%d ", val)
// 	}
// 	fmt.Println()
// }

step, resPoint := walkMaze(res, point{0, 0}, point{len(res) - 1, len(res[0]) - 1})

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


• 为爬虫实战项目做好准备
• 应用广泛，综合性强
• 面试常见的问题
• 用循环来创建一个二维slice
• 使用slice来实现队列
• 用Fscanf读取文件
• 对point的抽象
• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

kuc火

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

03-30 36
03-29 533
04-13 84
09-18 1540
03-22 558
06-07 2145