7-1 迷宫_算法

1635333441923
1635333456976

7-2 迷宫代码实现

  1. 6 5
  2. 0 1 0 0 0
  3. 0 0 0 1 0
  4. 0 1 0 1 0
  5. 1 1 1 0 0
  6. 0 1 0 0 1
  7. 0 1 0 0 0
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. )
  6. func readMaze(filename string) [][]int {
  7. file, err := os.Open(filename)
  8. if err != nil {
  9. panic(err)
  10. }
  11. var row, col int
  12. fmt.Fscanf(file, "%d %d", &row, &col)
  13. maze := make([][]int, row)
  14. for i := range maze {
  15. maze[i] = make([]int, col)
  16. for j := range maze[i] {
  17. fmt.Fscanf(file, "%d", &maze[i][j])
  18. }
  19. }
  20. return maze
  21. }
  22. type point struct {
  23. i, j int
  24. }
  25. var dirs = [4]point{
  26. {-1, 0}, {0, -1}, {1, 0}, {0, 1}}
  27. func (p point) add(r point) point {
  28. return point{p.i + r.i, p.j + r.j}
  29. }
  30. func (p point) at(grid [][]int) (int, bool) {
  31. if p.i < 0 || p.i >= len(grid) {
  32. return 0, false
  33. }
  34. if p.j < 0 || p.j >= len(grid[p.i]) {
  35. return 0, false
  36. }
  37. return grid[p.i][p.j], true
  38. }
  39. func walk(maze [][]int,
  40. start, end point) [][]int {
  41. steps := make([][]int, len(maze))
  42. for i := range steps {
  43. steps[i] = make([]int, len(maze[i]))
  44. }
  45. Q := []point{start}
  46. for len(Q) > 0 {
  47. cur := Q[0]
  48. Q = Q[1:]
  49. if cur == end {
  50. break
  51. }
  52. for _, dir := range dirs {
  53. next := cur.add(dir)
  54. val, ok := next.at(maze)
  55. if !ok || val == 1 {
  56. continue
  57. }
  58. val, ok = next.at(steps)
  59. if !ok || val != 0 {
  60. continue
  61. }
  62. if next == start {
  63. continue
  64. }
  65. curSteps, _ := cur.at(steps)
  66. steps[next.i][next.j] =
  67. curSteps + 1
  68. Q = append(Q, next)
  69. }
  70. }
  71. return steps
  72. }
  73. func main() {
  74. maze := readMaze("lang/maze/maze.in")
  75. steps := walk(maze, point{0, 0},
  76. point{len(maze) - 1, len(maze[0]) - 1})
  77. for _, row := range steps {
  78. for _, val := range row {
  79. fmt.Printf("%3d", val)
  80. }
  81. fmt.Println()
  82. }
  83. // TODO: construct path from steps
  84. }