print all possible solution for n queen problem in python

Solutions on MaxInterview for print all possible solution for n queen problem in python by the best coders in the world

showing results for - "print all possible solution for n queen problem in python"
Beatrice
11 Jun 2019
1### This code prints all possible solution for Nqueen problem
2
3
4# Function to check if two queens threaten each other or not
5def isSafe(mat, r, c):
6 
7    # return false if two queens share the same column
8    for i in range(r):
9        if mat[i][c] == 'Q':
10            return False
11 
12    # return false if two queens share the same `` diagonal
13    (i, j) = (r, c)
14    while i >= 0 and j >= 0:
15        if mat[i][j] == 'Q':
16            return False
17        i = i - 1
18        j = j - 1
19 
20    # return false if two queens share the same `/` diagonal
21    (i, j) = (r, c)
22    while i >= 0 and j < N:
23        if mat[i][j] == 'Q':
24            return False
25        i = i - 1
26        j = j + 1
27 
28    return True
29 
30 
31def printSolution(mat):
32    for i in range(N):
33        print(mat[i])
34    print()
35 
36 
37def nQueen(mat, r):
38 
39    # if `N` queens are placed successfully, print the solution
40    if r == N:
41        printSolution(mat)
42        return
43 
44    # place queen at every square in the current row `r`
45    # and recur for each valid movement
46    for i in range(N):
47 
48        # if no two queens threaten each other
49        if isSafe(mat, r, i):
50            # place queen on the current square
51            mat[r][i] = 'Q'
52 
53            # recur for the next row
54            nQueen(mat, r + 1)
55 
56            # backtrack and remove the queen from the current square
57            mat[r][i] = '–'
58 
59 
60if __name__ == '__main__':
61 
62    # `N × N` chessboard
63    N = 8
64 
65    # `mat[][]` keeps track of the position of queens in
66    # the current configuration
67    mat = [['–' for x in range(N)] for y in range(N)]
68 
69    nQueen(mat, 0)
70  
71