Skip to content

Commit 831558d

Browse files
Hetal KuvadiaAnupKumarPanwar
Hetal Kuvadia
authored andcommitted
TheAlgorithms#945 Backtracking Algorithms (TheAlgorithms#953)
* Adding nqueens.py for backtracking * Adding sum_of_subsets.py for backtracking * Update nqueens.py * Rename nqueens.py to n_queens.py * Deleting /other/n_queens.py
1 parent afb98e6 commit 831558d

File tree

3 files changed

+129
-77
lines changed

3 files changed

+129
-77
lines changed

backtracking/n_queens.py

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
'''
2+
3+
The nqueens problem is of placing N queens on a N * N
4+
chess board such that no queen can attack any other queens placed
5+
on that chess board.
6+
This means that one queen cannot have any other queen on its horizontal, vertical and
7+
diagonal lines.
8+
9+
'''
10+
solution = []
11+
12+
def isSafe(board, row, column):
13+
'''
14+
This function returns a boolean value True if it is safe to place a queen there considering
15+
the current state of the board.
16+
17+
Parameters :
18+
board(2D matrix) : board
19+
row ,column : coordinates of the cell on a board
20+
21+
Returns :
22+
Boolean Value
23+
24+
'''
25+
for i in range(len(board)):
26+
if board[row][i] == 1:
27+
return False
28+
for i in range(len(board)):
29+
if board[i][column] == 1:
30+
return False
31+
for i,j in zip(range(row,-1,-1),range(column,-1,-1)):
32+
if board[i][j] == 1:
33+
return False
34+
for i,j in zip(range(row,-1,-1),range(column,len(board))):
35+
if board[i][j] == 1:
36+
return False
37+
return True
38+
39+
def solve(board, row):
40+
'''
41+
It creates a state space tree and calls the safe function untill it receives a
42+
False Boolean and terminates that brach and backtracks to the next
43+
poosible solution branch.
44+
'''
45+
if row >= len(board):
46+
'''
47+
If the row number exceeds N we have board with a successful combination
48+
and that combination is appended to the solution list and the board is printed.
49+
50+
'''
51+
solution.append(board)
52+
printboard(board)
53+
print()
54+
return
55+
for i in range(len(board)):
56+
'''
57+
For every row it iterates through each column to check if it is feesible to place a
58+
queen there.
59+
If all the combinations for that particaular branch are successfull the board is
60+
reinitialized for the next possible combination.
61+
'''
62+
if isSafe(board,row,i):
63+
board[row][i] = 1
64+
solve(board,row+1)
65+
board[row][i] = 0
66+
return False
67+
68+
def printboard(board):
69+
'''
70+
Prints the boards that have a successfull combination.
71+
'''
72+
for i in range(len(board)):
73+
for j in range(len(board)):
74+
if board[i][j] == 1:
75+
print("Q", end = " ")
76+
else :
77+
print(".", end = " ")
78+
print()
79+
80+
#n=int(input("The no. of queens"))
81+
n = 8
82+
board = [[0 for i in range(n)]for j in range(n)]
83+
solve(board, 0)
84+
print("The total no. of solutions are :", len(solution))

backtracking/sum_of_subsets.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
'''
2+
The sum-of-subsetsproblem states that a set of non-negative integers, and a value M,
3+
determine all possible subsets of the given set whose summation sum equal to given M.
4+
5+
Summation of the chosen numbers must be equal to given number M and one number can
6+
be used only once.
7+
'''
8+
9+
def generate_sum_of_subsets_soln(nums, max_sum):
10+
result = []
11+
path = []
12+
num_index = 0
13+
remaining_nums_sum = sum(nums)
14+
create_state_space_tree(nums, max_sum, num_index, path,result, remaining_nums_sum)
15+
return result
16+
17+
def create_state_space_tree(nums,max_sum,num_index,path,result, remaining_nums_sum):
18+
'''
19+
Creates a state space tree to iterate through each branch using DFS.
20+
It terminates the branching of a node when any of the two conditions
21+
given below satisfy.
22+
This algorithm follows depth-fist-search and backtracks when the node is not branchable.
23+
24+
'''
25+
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
26+
return
27+
if sum(path) == max_sum:
28+
result.append(path)
29+
return
30+
for num_index in range(num_index,len(nums)):
31+
create_state_space_tree(nums, max_sum, num_index + 1, path + [nums[num_index]], result, remaining_nums_sum - nums[num_index])
32+
33+
'''
34+
remove the comment to take an input from the user
35+
36+
print("Enter the elements")
37+
nums = list(map(int, input().split()))
38+
print("Enter max_sum sum")
39+
max_sum = int(input())
40+
41+
'''
42+
nums = [3, 34, 4, 12, 5, 2]
43+
max_sum = 9
44+
result = generate_sum_of_subsets_soln(nums,max_sum)
45+
print(*result)

other/n_queens.py

-77
This file was deleted.

0 commit comments

Comments
 (0)