q=[[gets.chomp,""]] m={} while !q.empty? e=q.shift if e[0].size<=1 m[e[1]+e[0]]=true next end q<<[e[0][0..-2],e[1]+e[0][-1]] q<<[e[0][1..-1],e[1]+e[0][0]] end p m.size