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) (-(h-1)...h).to_a.product((-(w-1)...w).to_a) do |dy, dx| next if dx == 0 && dy == 0 _rect = rect.clone ok = true touched = false (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 < 0 || nx >= w || ny < 0 || ny >= h ok = false break end if _rect[y][x] == _rect[ny][nx] touched = true _rect[y][x] = "." _rect[ny][nx] = "." else ok = false break end end ok = ok && touched return true if ok end return false end puts ok?(rect, h, w) ? "YES" : "NO"