h, w = gets.split(' ').map(&:to_i) map = [] h.times do map.push(gets.split(' ').map(&:to_i)) end queue = [] gets.to_i.times do hh, ww, n = gets.split(' ').map(&:to_i) hh -= 1 ww -= 1 c = map[hh][ww] map[hh][ww] = n next if c == n queue.push([hh-1, ww]) if hh > 0 and map[hh-1][ww] == c queue.push([hh+1, ww]) if hh < h-1 and map[hh+1][ww] == c queue.push([hh, ww-1]) if ww > 0 and map[hh][ww-1] == c queue.push([hh, ww+1]) if ww < w-1 and map[hh][ww+1] == c while queue.empty?.! do hhh, www = queue.pop map[hhh][www] = n queue.push([hhh-1, www]) if hhh > 0 and map[hhh-1][www] == c queue.push([hhh+1, www]) if hhh < h-1 and map[hhh+1][www] == c queue.push([hhh, www-1]) if www > 0 and map[hhh][www-1] == c queue.push([hhh, www+1]) if www < w-1 and map[hhh][www+1] == c queue.uniq! end end map.each do |m| puts m.join(' ') end