class PPuzzle attr_reader :n def initialize(n,icol=[],irow=[],matrix=[]) @n = n @icol = icol @irow = irow @matrix = matrix end def read() @icol = @n.times.to_a @irow = @n.times.to_a @matrix = @n.times.map{gets.chomp.split.map{|s|s.to_i-1}} self end def clone() PPuzzle.new(@n,@icol.dup,@irow.dup,@matrix) end def at(r,c) @matrix[@irow[r]][@icol[c]] end def select_col(x) @n.times.map{|r|self.at(r,x)} end def select_row(y) @n.times.map{|c|self.at(y,c)} end def operate_col(x) pa = self.select_col(x) t = @icol.dup @n.times{|i| @icol[pa[i]] = t[i] } end def operate_row(y) pa = self.select_row(y) t = @irow.dup @n.times{|i| @irow[pa[i]] = t[i] } end def ==(other) @n.times.all?{|r| @n.times.all?{|c| self.at(r,c)==other.at(r,c) }} end end def search(b,k,t,v) return t==b if k==0 for i in b.select_col(k-1) v.push(i) s = t.clone s.operate_col(i) return true if search(b,k-1,s,v) v.pop v.push(i+b.n) s = t.clone s.operate_row(i) return true if search(b,k-1,s,v) v.pop end false end def cycle(p) t=[0]*p.size w=p.dup loop.with_index(1) {|_,cnt| p.size.times{|i| t[p[i]] = w[i] } break cnt if t == p t,w = [w,t] } end def solve(n,k,a,b) ops = [] search(b,k,a,ops) s=a.clone ans = [] ops.each{|op| if op