def is_valid_row?(row)
  (row.size-1).times do |j|
    return false if row[j]=='1' and row[j+1]=='1'
  end
  true
end

def valid_rows(w)
  (2**(w-1)).times.map do |i|
    b = sprintf("%0#{w-1}b0", i)  # last bit is always zero
  end.select do |row|
    is_valid_row?(row)
  end
end

$dp_count_valid_rows = {}

def count_valid_rows(w, ini, dx)
  key = "#{ini},#{dx}"
  if $dp_count_valid_rows[key]
    return $dp_count_valid_rows[key]
  end

  if dx == 0
    ans = valid_rows(w).count do |row|
      row[ini] == '0' and row[ini-1] == '0'
    end
  elsif dx == 1
    ans = valid_rows(w).count do |row|
      row[ini] == '1'
    end
  elsif dx == -1
    ans = valid_rows(w).count do |row|
      row[ini-1] == '1'
    end
  else
    ans = 0
  end
  $dp_count_valid_rows[key] = ans
  return $dp_count_valid_rows[key]
end

