広さ迷宮アルゴリズム-golang

21157 ワード

maze.inファイルは迷宮格を保存し、内容は以下の通りである.
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

maze.goコード実装
package main

import (
	"fmt"
	"os"
)

type point struct {
	i, j int
}

func (p point) add(step point) point {
	p.i += step.i
	p.j += step.j
	return p
}

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

func ReadMaze(path string) [][]int {
	file, err := os.Open(path)
	if err != nil {
		fmt.Println(err)
		os.Exit(2)
	}
	defer func(){
		file.Close()
	}()
	var row, col int
	_, err = fmt.Fscanf(file, "%d %d", &row, &col)
	if err != nil {
		fmt.Println(err)
		os.Exit(3)
	}
	maze := make([][]int, row)
	for i := range maze {
		maze[i] = make([]int, col)
		for j := range maze[i] {
			_, err = fmt.Fscanf(file, "%d", &maze[i][j])
			if err != nil {
				fmt.Println(err)
				os.Exit(4)
			}
		}
	}
	return maze
}
//                 
var direction = [4]point{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}

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         
	Q := []point{start}

	for len(Q) > 0 {
		current_location := Q[0]
		Q = Q[1:]
		//     
		if current_location == end {
			break
		}
		for _, val := range direction {
			// 1.            
			// 2.      1            

			//     
			next := current_location.add(val)
			//    next          
			location, bl := next.at(maze)
			//                    
			if !bl || location == 1 {
				continue
			}
			//           
			location, bl = next.at(steps)
			if !bl || location != 0 {
				continue
			}
			//         
			if next == start {
				continue
			}
			//                       
			curSteps, _ := current_location.at(steps)
			//                 1
			steps[next.i][next.j] = curSteps + 1
			//                     
			Q = append(Q, next)
		}
	}
	return steps
}

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


最終結果
  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