Skip to content

Instantly share code, notes, and snippets.

@shubham-kshetre
Created November 5, 2023 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shubham-kshetre/41f2b6e109e8a1b06c1e136c513ec16f to your computer and use it in GitHub Desktop.
Save shubham-kshetre/41f2b6e109e8a1b06c1e136c513ec16f to your computer and use it in GitHub Desktop.
A5
class NQBacktracking:
def __init__(self, x_, y_):
self.ld = [0] * 30
self.rd = [0] * 30
self.cl = [0] * 30
self.x = x_
self.y = y_
def printSolution(self, board):
print(
"N Queen Backtracking Solution:\nGiven initial position of 1st queen at row:",
self.x,
"column:",
self.y,
"\n",
)
for line in board:
print(" ".join(map(str, line)))
def solveNQUtil(self, board, col):
N = 8 # You need to define N here or pass it as an argument to methods.
if col >= N:
return True
if col == self.y:
return self.solveNQUtil(board, col + 1)
for i in range(N):
if i == self.x:
continue
if (self.ld[i - col + N - 1] != 1 and self.rd[i + col] != 1) and self.cl[i] != 1:
board[i][col] = 1
self.ld[i - col + N - 1] = self.rd[i + col] = self.cl[i] = 1
if self.solveNQUtil(board, col + 1):
return True
board[i][col] = 0
self.ld[i - col + N - 1] = self.rd[i + col] = self.cl[i] = 0
return False
def solveNQ(self):
N = 8 # You need to define N here or pass it as an argument to methods.
board = [[0 for _ in range(N)] for _ in range(N)]
board[self.x][self.y] = 1
self.ld[self.x - self.y + N - 1] = self.rd[self.x + self.y] = self.cl[self.x] = 1
if not self.solveNQUtil(board, 0):
print("Solution does not exist")
return False
self.printSolution(board)
return True
if __name__ == "__main__": # Correct the condition for main execution
N = 8
x, y = 3, 2
NQBt = NQBacktracking(x, y)
NQBt.solveNQ()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment