@goal = [*1..15] + [0] def sol a, idx, memo if a == @goal return true end if idx % 4 != 0 && !memo[a[idx - 1] - 1] memo[a[idx - 1] - 1] = true a[idx] = a[idx - 1] a[idx - 1] = 0 if sol(a, idx - 1, memo) return true end memo[a[idx] - 1] = false a[idx - 1] = a[idx] a[idx] = 0 end if idx % 4 != 3 && !memo[a[idx + 1] - 1] memo[a[idx + 1] - 1] = true a[idx] = a[idx + 1] a[idx + 1] = 0 if sol(a, idx + 1, memo) return true end memo[a[idx] - 1] = false a[idx + 1] = a[idx] a[idx] = 0 end if idx >= 4 && !memo[a[idx - 4] - 1] memo[a[idx - 4] - 1] = true a[idx] = a[idx - 4] a[idx - 4] = 0 if sol(a, idx - 4, memo) return true end memo[a[idx] - 1] = false a[idx - 4] = a[idx] a[idx] = 0 end if idx / 4 != 3 && !memo[a[idx + 4] - 1] memo[a[idx + 4] - 1] = true a[idx] = a[idx + 4] a[idx + 4] = 0 if sol(a, idx + 4, memo) return true end memo[a[idx] - 1] = false a[idx + 4] = a[idx] a[idx] = 0 end return false end a = STDIN.map{|s|s.split.map(&:to_i)}.flatten if sol(a, a.index(0), Array.new(15,false)) puts 'Yes' else puts 'No' end