n = int(input())
sq = [list(map(int, input())) for _ in range(n)]
def is_possible(lst):
    for i in range(n):
        row = [lst[i][j] for j in range(n) if lst[i][j] > 0 ]
        if any(not e in range(1, n + 1) for e in row) or any(row.count(e) != 1 for e in row):
            return False
    for j in range(n):
        col = [lst[i][j] for i in range(n) if lst[i][j] > 0]
        if any(not e in range(1, n + 1) for e in col) or any(col.count(e) != 1 for e in col):
            return False
    return True

def is_ok(lst):
    for i in range(n):
        row = [lst[i][j] for j in range(n)]
        if any(not e in range(1, n + 1) for e in row) or any(row.count(e) != 1 for e in row):
            return False
    for j in range(n):
        col = [lst[i][j] for i in range(n)]
        if any(not e in range(1, n + 1) for e in col) or any(col.count(e) != 1 for e in col):
            return False
    return True
    
def full(l):
    return all(x != 0 for x in l)
print(sq)
step = 0
_sum = -1
def make_hash(lst):
    return '\n'.join(''.join(map(str, r)) for r in lst)

def get_pivot(lst):
    m = sorted([[x, i] for i, x in enumerate(lst)], key=lambda x: x[0].count(0))
    i = 0
    while i < len(lst) and all(x > 0 for x in m[i][0]):
        i += 1
    if i == len(lst):
        return (-1, -1)
    j = 0
    while j < len(lst[i]) and lst[i][j] != 0:
        j += 1
    if j == len(lst):
        return (-1, -1)
    else:
        return (i, j)
        
q = [tuple([tuple(r) for r in sq])]
seen = set([make_hash(sq)])

ans = 0
while len(q) > 0:
    ele = q.pop(0)
    b = is_possible(ele)
    if not b:
        print(0)
        exit()
    if is_ok(ele):
        ans += 1
    i, j = get_pivot(ele)
    if i != -1 or j != -1:
        cand = set(range(1, n + 1))
        for ee in ele[i]:
            if ee > 0:
                cand.discard(ee)
        for row in range(n):
            if ele[row][j] > 0:
                cand.discard(ele[row][j])
        for x in cand:
            cpy = [list(r) for r in ele]
            cpy[i][j] = x
            hsh = make_hash(cpy)
            if is_possible(cpy) and not hsh in seen:
                q.append(tuple([tuple(r) for r in cpy]))

print(ans)

Embed on website

To embed this program on your website, copy the following code and paste it into your website's HTML: