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 touched = false (0...h).to_a.product((0...w).to_a) do |y, x| next if _rect[y][x] == "." ny = (y + dy) % h nx = (x + dx) % w 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"