h, w = gets.not_nil!.split(" ").map{|x| x.to_i} rect = [] of Array(String) 1.upto(h) do |i| rect << gets.not_nil!.split("") end def ok?(rect, h, w) (0...h).to_a.product((0...w).to_a) do |dy, dx| next if dx == 0 && dy == 0 _rect = rect.clone ok = true (0...h).to_a.product((0...w).to_a) do |y, x| next if _rect[y][x] == "." ny = y + dy nx = x + dx if nx >= w || ny >= h ok = false break end if _rect[y][x] == _rect[ny][nx] _rect[y][x] = "." _rect[ny][nx] = "." else ok = false break end end return true if ok end return false end puts ok?(rect, h, w) ? "YES" : "NO"