Skip to content

Instantly share code, notes, and snippets.

@sanchojaf
Last active September 9, 2020 15:20
Show Gist options
  • Save sanchojaf/5590abc7a58a3ebdbffd522f60e58eb7 to your computer and use it in GitHub Desktop.
Save sanchojaf/5590abc7a58a3ebdbffd522f60e58eb7 to your computer and use it in GitHub Desktop.
Rat In A Maze Puzzle [backtracking, ruby]
# Given a maze, NxN matrix. A rat has to find a path from source to destination.
# maze[0][0] (left top corner)is the source and maze[N-1][N-1](right bottom corner)
# is destination. There are few cells which are blocked, means rat cannot enter
# into those cells. Rat can move in any direction (left, right, up and down).
require 'rspec/autorun'
class RatInMaze
def initialize(maze)
@maze = maze
@n = maze.size
@board = Array.new(@n) { Array.new(@n, false) }
@variantions =
[[ 1, 0, 'down', 'up' ],
[ 0, 1, 'right','left' ],
[-1, 0, 'up', 'down' ],
[ 0,-1, 'left', 'right']]
end
def solve
find_path(0, 0, 'down') ? @board : 'NO PATH FOUND'
end
def find_path(row, col, direction)
return false unless can_move?(row, col)
@board[row][col] = true
return true if row == @n-1 && col == @n-1
@variantions.each do |var_row, var_col, new_direction, opposite|
return true if direction != opposite && find_path(row+var_row, col+var_col, new_direction)
end
@board[row][col] = false
false
end
def can_move?(row, col)
row.between?(0,@n-1) && col.between?(0,@n-1) && @maze[row][col] != 0 && !@board[row][col]
end
end
RSpec.describe RatInMaze do
let(:maze) do
[[ 1, 0, 1, 1, 1 ],
[ 1, 1, 1, 0, 1 ],
[ 1, 0, 0, 1, 1 ],
[ 1, 1, 0, 1, 0 ],
[ 0, 1, 0, 1, 1 ]]
end
let(:result) do
[[true, false, true, true, true],
[true, true, true, false, true],
[false, false, false, true, true],
[false, false, false, true, false],
[false, false, false, true, true]]
end
it '#solve' do
r = RatInMaze.new(maze)
expect(r.solve).to eq result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment