class Calc0228 def initialize(args) args = args.map { |l| l.chomp.split(/\s+/) } @as = args.map { |l| l.map(&:to_i) } end def calc as = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,0]] stack = [[as, []]] until stack.empty? as, used = stack.pop return true if goal?(as) x, y = find0(as) cands = [[x - 1, y], [x, y - 1], [x + 1, y], [x, y + 1]].select { |x2, y2| (0..3).include?(x2) && (0..3).include?(y2) && !used.include?(as[y2][x2]) } cands.each do |x2, y2| as2 = dup(as) as2[y][x], as2[y2][x2] = as2[y2][x2], as2[y][x] stack.push([as2, used + [as2[y][x]]]) end end false end def goal?(as) @as.zip(as).all? { |r1, r2| r1 == r2 } end def find0(as) as.each_with_index do |r, y| r.each_with_index do |a, x| return x, y if a == 0 end end end def dup(as) as.dup.map { |r| r.dup } end def run calc ? 'Yes' : 'No' end end puts Calc0228.new(STDIN.readlines).run if __FILE__ == $0