Python 解决 8 皇后问题

最近在学Python,很多语法都跟C/C++不同。下面是用Python写的八皇后问题,结果都以追加方式写入了当前文件夹下的 result.txt。


# coding = utf-8

# n皇后问题

def conflict(s, x, y):
    for i in range(y):
        if (abs(s[i] - x) == y - i) or (x == s[i]):
            return True
    return False


def searchAnswer(y, n, s, ct, f):
    if y == n:
        ct[0] += 1
        print('')
        print('Solution', ct[0], ':')
        f.write('\nSolution ' + str(ct[0]) + ':\n')
        for i in range(n):
            ans = ''
            for j in range(n):
                if solution[i] == j:
                    ans += 'X '
                else:
                    ans += 'O '
            print(ans)
            f.write(ans+'\n')

    for x in range(n):
        if not conflict(s, x, y):
            s[y] = x
            searchAnswer(y + 1, n, s, ct, f)


while True:
    solution = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    counter = [0]
    print('------------N Queens-------------')
    n = int(input('Enter the N: '))
    if 0 == n: break

    f = open("result.txt", "a")
    f.write('\n------------- ' + str(n) + ' Queens-------------\n')
    for x in range(n):
        solution[0] = x
        searchAnswer(1, n, solution, counter, f)

    f.close()



你可能感兴趣的:(Python)