Skip to content

Instantly share code, notes, and snippets.

@yfractal
Created October 22, 2014 05:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yfractal/9fd567789ec0ef1534d0 to your computer and use it in GitHub Desktop.
Save yfractal/9fd567789ec0ef1534d0 to your computer and use it in GitHub Desktop.
bricks
# coding: utf-8
class Board
def initialize(c, r)
@column = c
@row = r
@board = c.times.map { Array.new(r,false)}
end
def fill!(c, r)
@board[c][r] = true;
end
def filled?(c, r)
@board[c][r]
end
def c
@column
end
def r
@row
end
def can_be_filled?(c, r)
if (c < 0 or r < 0) or (c >= @column or r >= @row) or filled?(c, r)
return false
else
return true
end
end
def board
@board
end
def board=(board)
@board = board
end
def full?
@board.each do |c|
c.each do |block|
return false unless block
end
end
return true
end
end
def deep_copy(board)
new_board = Board.new(board.c, board.r)
new_board.board = board.board.map{|r| r.dup}
new_board
end
def deep_copy_bricks(bricks)
new_bricks = Bricks.new
new_bricks.bricks = bricks.bricks.map{ |brick| brick.dup }
new_bricks.parent = bricks.parent
new_bricks
end
class Bricks
attr_accessor :parent, :bricks
def initialize
@bricks = []
@parent
end
def add_brick(c, r)
@bricks << [c, r]
end
def full?
@bricks.length == 5
end
end
# save board
def try_next(board, c, r, bricks)
if board.full?
puts "board full"
puts bricks.bricks.length
if bricks.full?
@@success_brickses << bricks
end
return true
end
if bricks.full?
new_brick_t = Bricks.new()
new_brick_t.parent = bricks
bricks = new_brick_t
end
[1,0, -1].each do |c_diff| # 尝试过每个方向,没有可能的解
[1,0,-1].each do |r_diff|
new_c = c + c_diff
new_r = r + r_diff
if ! (c_diff == 0 and r_diff == 0) and board.can_be_filled?(new_c, new_r)
copyed_board = deep_copy(board)
copyed_board.fill!(new_c, new_r)
new_bricks = deep_copy_bricks(bricks)
new_bricks.add_brick(new_c, new_r)
try_next(copyed_board, new_c, new_r, new_bricks)
end
end
end
return false
end
@@success_brickses = []
board = Board.new(3,5)
bricks = Bricks.new
bricks.add_brick(0, 0)
board.fill!(0, 0)
try_next(board, 0, 0, bricks)
@@success_brickses
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment