"""BTVN: mô hình xếp Hậu theo SGK Chuyên đề Tin học11 CS, Python3.

python3 g11-cs-xep-hau.py 4
python3 g11-cs-xep-hau.py 4 --hang-tu-duoi
python3 g11-cs-xep-hau.py 13 --chi-dem
A[k] là hàng của quân tại cột k, chỉ số 0..n-1.
Bản thực hành nhận 1..13; chỉ in bàn cờ khi n<=8 để hạn chế đầu ra.
"""
import argparse

n = 0
A = []
ncount = 0
show_results = True
from_bottom = False


def check(A, i, j):
    for k in range(j):
        if A[k] == i:
            return False
        if abs(A[k] - i) == abs(j - k):
            return False
    return True


def showQueen(A, from_bottom=False):
    n = len(A)
    rows = range(n - 1, -1, -1) if from_bottom else range(n)
    for i in rows:
        for j in range(n):
            print(1 if A[j] == i else 0, end=' ')
        print()


def trynext(k):
    global ncount
    if k == n:
        ncount += 1
        if show_results:
            print('Phương án', ncount, ':', A)
            showQueen(A, from_bottom)
    else:
        for i in range(n):
            if check(A, i, k):
                A[k] = i
                trynext(k + 1)


def main():
    global n, A, ncount, show_results, from_bottom
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('n', type=int)
    parser.add_argument('--chi-dem', action='store_true')
    parser.add_argument('--hang-tu-duoi', action='store_true')
    args = parser.parse_args()
    if not 1 <= args.n <= 13:
        parser.error('Bản thực hành nhận n từ 1 đến 13.')
    if args.n > 8 and not args.chi_dem:
        parser.error('Với n>8, dùng --chi-dem để tránh in quá nhiều bàn cờ.')
    n = args.n
    A = [0] * n
    ncount = 0
    show_results = not args.chi_dem
    from_bottom = args.hang_tu_duoi
    trynext(0)
    print(f'Q({n}) = {ncount}')


if __name__ == '__main__':
    main()
