lines = STDIN.readlines h, w = lines[0].split.map {|x| x.to_i} s = [] h.times {|i| s << lines[i + 1].chomp} q = lines[h + 1].chomp.to_i q_array = [] q.times {|i| q_array << lines[h + i + 2].split.map {|x| x.to_i}.to_a} def search_w(y, x, a, b, c, d) total = 0 total += search_w_dir y, x, -1, 0, a, b, c, d total += search_w_dir y, x, 1, 0, a, b, c, d total += search_w_dir y, x, 0, -1, a, b, c, d total += search_w_dir y, x, 0, 1, a, b, c, d total end def search_w_dir(y, x, j, i, a, b, c, d) w_count = 0 while a <= y && y <= c && b <= x && x <= d if s[y][x] == "w" w_count += 1 end y += j x += i end w_count * (w_count - 1) / 2 end q_array.each do |a, b, c, d| total = 0 a.upto(c) do |y| b.upto(d) do |x| if s[y][x] == "c" total += search_w y, x, a, b, c, d end end end puts total end