`
googya
  • 浏览: 140299 次
  • 性别: Icon_minigender_1
  • 来自: 汉川
社区版块
存档分类
最新评论

老鼠走迷宫

阅读更多
说明
老鼠走迷宫是递回求解的基本题型,我们在二维阵列中使用2表示迷宫墙壁,使用1来表示老鼠的行走路径,试以程式求出由入口至出口的路径。
解法
老鼠的走法有上、左、下、右四个方向,在每前进一格之后就选一个方向前进,无法前进时退回选择下一个可前进方向,如此在阵列中依序测试四个方向,直到走到出口为止,这是递回的基本题,请直接看代码应就可以理解。


class Point
  attr_accessor :x,:y
  def initialize(x,y)
    @x=x
    @y=y
  end
end

class Maze
  def  initialize(maze,end_1)
    @maze=maze
    @end=end_1
  end

  def isArrived
    @maze[@end.x][@end.y]==1
  end

  def isEmpty(p)
    @maze[p.x][p.y]==0
  end

  def step(p)
    @maze[p.x][p.y]=1
  end

  def empty(p)
    @maze[p.x][p.y]=0
  end

  def print_p
    unless @maze.length
      exit
    end

    for i in 0..@maze..length
      for j in 0..@maze[0]..length
        if @maze[i][j]==2
          print "█"
        elsif @maze[i][j]==1
          print "◇"
        else
          print "  "
        end
      end
      print "\n"
    end

  end
end

class Mouse
#  def initialize(maze,p)
#    @maze=maze
#    @p=p
#  end
  def self.go(maze,p)
    maze.step(p)
    self.test(maze,Point.new(p.x,p.y+1))
    self.test(maze,Point.new(p.x+1,p.y))
    self.test(maze,Point.new(p.x,p.y-1))
    self.test(maze,Point.new(p.x-1,p.y))
    if !maze.isArrived
      maze.empty(p)
    end
  end

  def self.test(maze,p)
    if !maze.isArrived and maze.isEmpty(p)
      self.go(maze,p)
    end
  end
end

@maze= Maze.new(Array[
                Array[2, 2, 2, 2, 2, 2, 2],
                Array[2, 0, 0, 0, 0, 0, 2],
                Array[2, 0, 2, 0, 2, 0, 2],
                Array[2, 0, 0, 2, 0, 2, 2],
                Array[2, 2, 0, 2, 0, 2, 2],
                Array[2, 0, 0, 0, 0, 0, 2],
                Array[2, 2, 2, 2, 2, 2, 2]
             ], Point.new(5, 5))
Mouse.go(@maze,Point.new(1,1))
if(!@maze.isArrived)
   println("沒找到出口")
end
@maze.print_p

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics