Guest User

Untitled

a guest
Oct 23rd, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. # Given a maze, NxN matrix. A rat has to find a path from source to destination.
  2. # maze[0][0] (left top corner)is the source and maze[N-1][N-1](right bottom corner)
  3. # is destination. There are few cells which are blocked, means rat cannot enter
  4. # into those cells. Rat can move in any direction (left, right, up and down).
  5.  
  6. class RatInMaze
  7. def initialize(maze, n)
  8. @maze = maze
  9. @n = n
  10. @board = Array.new(n) { Array.new(n, false) }
  11. end
  12.  
  13. def solve
  14. if find_path(0, 0, "down") then print_board else puts "NO PATH FOUND" end
  15. end
  16.  
  17. def find_path(row, col, direction)
  18. @board[row][col] = true
  19. return true if row == @n-1 and col == @n-1
  20. variantions = [[1,0,'down','up'],[0,1,'right','left'],[-1,0,'up','down'],[0,-1,'left','right']]
  21. variantions.each do |var_row, var_col, new_direction, opposite|
  22. if can_move?(row+var_row, col+var_col)
  23. return true if direction != opposite && find_path(row+var_row, col+var_col, new_direction)
  24. end
  25. end
  26. @board[row][col] = false
  27. end
  28.  
  29. def can_move?(row, col)
  30. row.between?(0,@n-1) and col.between?(0,@n-1) and @maze[row][col] != 0
  31. end
  32.  
  33. def print_board
  34. puts "Board:"
  35. @board.each do |row|
  36. row.each do |value|
  37. print value ? 'R' : '.'
  38. end
  39. puts
  40. end
  41. end
  42.  
  43. end
  44.  
  45.  
  46. n = 5
  47. maze = [ [ 1, 0, 1, 1, 1 ],
  48. [ 1, 1, 1, 0, 1 ],
  49. [ 0, 0, 0, 1, 1 ],
  50. [ 0, 0, 0, 1, 0 ],
  51. [ 0, 0, 0, 1, 1 ]]
  52. r = RatInMaze.new(maze, n)
  53. r.solve
Advertisement
Add Comment
Please, Sign In to add comment