Created
July 4, 2013 11:35
-
-
Save ackintosh/5926969 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pry' | |
class Block | |
(class << self; self; end;).class_eval do | |
def output(input) | |
ary = input.each_line.inject([]) { |result, line| result << line.chomp! } | |
result = [] | |
loop do | |
break if ary.first == '0 0' | |
result << judge(ary) | |
end | |
return result.join("\n") | |
end | |
def judge(ary) | |
w, h = ary.shift.split(' ') | |
xs, ys = ary.shift.split(' ') | |
xg, yg = ary.shift.split(' ') | |
n = ary.shift | |
# convert to Fixnum | |
w, h, xs, ys, xg, yg, n = [w, h, xs, ys, xg, yg, n].map { |i| i.to_i } | |
blocks = [] | |
n.times do | |
c, d, x, y = ary.shift.split(' ').map { |i| i.to_i } | |
blocks << {c: c, d: d, x: x, y: y} | |
end | |
map = build_map(w, h, blocks) | |
map.labyrinth?(xs, ys, xg, yg) ? 'OK' : 'NG' | |
end | |
def build_map(w, h, blocks) | |
# initialize map | |
map = Map.new(w, h) | |
# put blocks on map | |
blocks.each { |b| map.set! b } | |
map | |
end | |
end | |
class Map < Hash | |
def initialize(w, h) | |
w.times do |n| | |
row = Hash.new | |
h.times { |m| row[m + 1] = nil } | |
self[n + 1] = row | |
end | |
end | |
def set!(block) | |
xe = (block[:d] == 0) ? block[:x] + 3 : block[:x] + 1 | |
ye = (block[:d] == 0) ? block[:y] + 1 : block[:y] + 3 | |
(block[:y]..ye).each do |y| | |
(block[:x]..xe).each { |x| self[y][x] = block[:c] } | |
end | |
end | |
def labyrinth?(xs, ys, xg, yg) | |
result = scan_color(self[ys][xs], xs, ys) do |x, y| | |
((xs == x) and (ys == y)) | |
end | |
result | |
end | |
def scan_color(color, x, y, &is_goal) | |
return false unless x <= self.first.size | |
return false unless y <= self.size | |
return false unless color == self[y][x] | |
return true if is_goal.call(x, y) | |
scan_color(color, x - 1, y, is_goal) | |
scan_color(color, x + 1, y, is_goal) | |
scan_color(color, x, y + 1, is_goal) | |
scan_color(color, x, y - 1, is_goal) | |
end | |
end | |
end | |
input = <<'EOS' | |
20 20 | |
1 1 | |
9 9 | |
7 | |
2 0 1 1 | |
5 1 1 3 | |
2 1 3 3 | |
1 1 5 2 | |
5 1 7 3 | |
2 0 2 7 | |
2 0 6 8 | |
20 20 | |
9 9 | |
1 1 | |
6 | |
2 0 1 1 | |
1 0 5 1 | |
2 1 1 3 | |
5 0 1 7 | |
3 1 5 5 | |
4 1 8 5 | |
0 0 | |
EOS | |
puts Block.output(input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment