0% found this document useful (0 votes)
23 views29 pages

Remaing Daa

dfigjfxgifgihdfsk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views29 pages

Remaing Daa

dfigjfxgifgihdfsk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Date: Program no: Page no:

1. Perform the traversal algorithms for a given tree in a Pre order.


AIM: Python program Perform the traversal algorithms for a given tree in a Pre order.

DESCRIPTION:

The program constructs a binary tree based on user input and then performs pre-order traversal on the constructed
tree. Pre-order traversal visits each node in the tree in the order: current node, left subtree, right subtree.

ALGORITHM:

1. Define a class TreeNode to represent a node in the binary tree. Each node has a value and references to its left
and right children.
2. Define a function build_tree() to construct the binary tree. This function prompts the user to enter the value
of each node. If the user enters an empty value, it indicates a null node.
• Prompt the user to enter the value of the root node.
• If the entered value is empty, return None (indicating a null node).
• Otherwise, create a new TreeNode with the entered value as its value.
• Recursively call build_tree() to construct the left and right subtrees, then assign them to the left and
right children of the current node.
• Return the constructed root node.
3. Define a function pre_order_traversal(root) to perform pre-order traversal on the binary tree. This function
takes the root node of the tree as input.
• If the root node is None, return.
• Print the value of the current node.
• Recursively call pre_order_traversal() on the left subtree.
• Recursively call pre_order_traversal() on the right subtree.

TIME COMPLEXITY:

The time complexity of the provided code is ( O(n) , where n is the number of nodes in the binary tree. This
complexity arises from the pre-order traversal operation, which visits each node once. The building of the binary tree
also contributes to the time complexity, but it is overshadowed by the traversal operation. Therefore, the overall time
complexity is O(n) .

PROGRAM CODE:

class TreeNode:

def __init__(self, value):

self.val = value

self.left = None

self.right = None

def build_tree():

root_val = input("Enter the value of the root node: ")

if not root_val:

return None

root = TreeNode(int(root_val))

print(f"Enter the left child of {root.val} (Enter empty value to indicate a null node):")

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

root.left = build_tree()

print(f"Enter the right child of {root.val} (Enter empty value to indicate a null node):")

root.right = build_tree()

return root

def pre_order_traversal(root):

if root is None:

return

print(root.val, end=" ")

pre_order_traversal(root.left)

pre_order_traversal(root.right)

if __name__ == "__main__":

print("Enter the elements of the tree (Enter empty value to indicate a null node):")

root = build_tree()

print("\nPerforming Pre-order Traversal:")

pre_order_traversal(root)

EXPECTED OUTPUT:

Enter the elements of the tree (Enter empty value to indicate a null node):

Enter the value of the root node: 20

Enter the left child of 20 (Enter empty value to indicate a null node):

Enter the value of the root node: 34

Enter the left child of 34 (Enter empty value to indicate a null node):

Enter the value of the root node: 56

Enter the left child of 56 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 56 (Enter empty value to indicate a null node):

Enter the value of the root node: 78

Enter the left child of 78 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 78 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 34 (Enter empty value to indicate a null node):

Enter the value of the root node: 30

Enter the left child of 30 (Enter empty value to indicate a null node):

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

Enter the value of the root node:

Enter the right child of 30 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 20 (Enter empty value to indicate a null node):

Enter the value of the root node: 10

Enter the left child of 10 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 10 (Enter empty value to indicate a null node):

Enter the value of the root node:

Performing Pre-order Traversal:

20 34 56 78 30 10

EXECUTED OUTPUT:

RESULT: The above Python program To Perform the traversal algorithms for a given tree in a Pre order is executed
successfully.

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

Perform the traversal algorithms for a given tree in a Post order.

AIM: Python program Perform the traversal algorithms for a given tree in a Post order.

DESCRIPTION:

This Python program performs post-order traversal for a given binary tree. Post-order traversal visits each node in the
tree in the order: left subtree, right subtree, current node. The program takes input from the user to construct the
binary tree and then performs the post-order traversal..

ALGORITHM:

1. Define a class TreeNode to represent a node in the binary tree. Each node has a value and references to its left
and right children.
2. Define a function build_tree() to construct the binary tree recursively. This function prompts the user to enter
the value of each node. If the user enters an empty value, it indicates a null node.
3. Define a function post_order_traversal(root) to perform post-order traversal on the binary tree. This function
takes the root node of the tree as input.
• If the root node is None, return.
• Recursively call post_order_traversal() on the left subtree.
• Recursively call post_order_traversal() on the right subtree.
• Print the value of the current node.

TIME COMPLEXITY:

The time complexity of this program is (O(n), where n is the number of nodes in the binary tree. This is because each
node is visited exactly once during the post-order traversal.

PROGRAM CODE:

class TreeNode:

def __init__(self, value):

self.val = value

self.left = None

self.right = None

def build_tree():

root_val = input("Enter the value of the root node: ")

if not root_val:

return None

root = TreeNode(int(root_val))

print(f"Enter the left child of {root.val} (Enter empty value to indicate a null node):")

root.left = build_tree()

print(f"Enter the right child of {root.val} (Enter empty value to indicate a null node):")

root.right = build_tree()

return root

def post_order_traversal(root):

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

if root is None:

return

post_order_traversal(root.left)

post_order_traversal(root.right)

print(root.val, end=" ")

# Main function

if __name__ == "__main__":

print("Enter the elements of the tree (Enter empty value to indicate a null node):")

root = build_tree()

print("\nPerforming Post-order Traversal:")

post_order_traversal(root)

EXPECTED OUTPUT:

Enter the elements of the tree (Enter empty value to indicate a null node):

Enter the value of the root node: 20

Enter the left child of 20 (Enter empty value to indicate a null node):

Enter the value of the root node: 10

Enter the left child of 10 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 10 (Enter empty value to indicate a null node):

Enter the value of the root node: 30

Enter the left child of 30 (Enter empty value to indicate a null node):

Enter the value of the root node: 5

Enter the left child of 5 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 5 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 30 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 20 (Enter empty value to indicate a null node):

Enter the value of the root node: 90

Enter the left child of 90 (Enter empty value to indicate a null node):

Enter the value of the root node: 20

Enter the left child of 20 (Enter empty value to indicate a null node):

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

Enter the value of the root node: 32

Enter the left child of 32 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 32 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 20 (Enter empty value to indicate a null node):

Enter the value of the root node: 43

Enter the left child of 43 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 43 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 90 (Enter empty value to indicate a null node):

Enter the value of the root node:

Performing Post-order Traversal:

5 30 10 32 43 20 90 20

EXECUTED OUTPUT:

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

RESULT: The above Python program To Perform the traversal algorithms for a given tree in a POST order is executed
successfully.

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

2. Perform the traversal algorithms for a given tree in a In order.


AIM: Python program Perform the traversal algorithms for a given tree in a In order.

DESCRIPTION:

This Python program performs in-order traversal for a given binary tree. In-order traversal visits each node in the tree
in the order: left subtree, current node, right subtree. The program takes input from the user to construct the binary
tree and then performs the in-order traversal.

ALGORITHM:

1. Define a class TreeNode to represent a node in the binary tree. Each node has a value and references to its
left and right children.
2. Define a function build_tree() to construct the binary tree recursively. This function prompts the user to enter
the value of each node. If the user enters an empty value, it indicates a null node.
3. Define a function in_order_traversal(root) to perform in-order traversal on the binary tree. This function
takes the root node of the tree as input.
• If the root node is None, return.
• Recursively call in_order_traversal() on the left subtree.
• Print the value of the current node.
• Recursively call in_order_traversal() on the right subtree.

TIME COMPLEXITY:

The time complexity of this program is O(n), where n is the number of nodes in the binary tree. This is because each
node is visited exactly once during the in-order traversal..

PROGRAM CODE:

class TreeNode:

def __init__(self, value):

self.val = value

self.left = None

self.right = None

def build_tree():

root_val = input("Enter the value of the root node: ")

if not root_val:

return None

root = TreeNode(int(root_val))

print(f"Enter the left child of {root.val} (Enter empty value to indicate a null node):")

root.left = build_tree()

print(f"Enter the right child of {root.val} (Enter empty value to indicate a null node):")

root.right = build_tree()

return root

def in_order_traversal(root):

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

if root is None:

return

in_order_traversal(root.left)

print(root.val, end=" ")

in_order_traversal(root.right)

if __name__ == "__main__":

print("Enter the elements of the tree (Enter empty value to indicate a null node):")

root = build_tree()

print("\nPerforming In-order Traversal:")

in_order_traversal(root)

EXPECTED OUTPUT:

Enter the elements of the tree (Enter empty value to indicate a null node):

Enter the value of the root node: 1

Enter the left child of 1 (Enter empty value to indicate a null node):

Enter the value of the root node: 3

Enter the left child of 3 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 3 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 1 (Enter empty value to indicate a null node):

Enter the value of the root node: 4

Enter the left child of 4 (Enter empty value to indicate a null node):

Enter the value of the root node:

Enter the right child of 4 (Enter empty value to indicate a null node):

Enter the value of the root node:

Performing In-order Traversal:

314

EXECUTED OUTPUT:

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

RESULT: The above Python program To Perform the traversal algorithms for a given tree in a IN order is executed
successfully.

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

WRITE A PYHON PROGRAM TO FIND THE JOB SEQUENCE WITH DEADLINE.

AIM : To Write A Python Program To Find The Job Sequence With Deadline.

DESCRIPTION :

The program aims to find the maximum profit sequence of jobs within their deadlines, given the details of each job
(job name, deadline, and profit) and the number of time slots available. It uses a greedy approach, sorting the jobs
based on their profit in decreasing order and then scheduling them based on their deadlines and available time slots.

ALGORITHM:

• Input: Take input from the user for the number of jobs, details of each job (job name, deadline, and profit),
and the number of time slots available.
• Sorting: Sort all jobs according to decreasing order of profit.
• Initialization: Initialize an array result of size t to keep track of free time slots and an array job of size t to
store the sequence of jobs scheduled within the available time slots.
• Scheduling Jobs: Iterate through all given jobs.
• For each job, find a free time slot starting from the last possible slot before its deadline.
• Assign the job to the first available time slot and mark the time slot as occupied.
• Output: Print the sequence of jobs scheduled within the available time slots.

TIME COMPLEXITY:

Sorting Jobs: Sorting all jobs based on their profit requires O(nlogn) time, where n is the number of jobs.

Scheduling Jobs: Iterating through all jobs and finding free time slots for each job takes O(n⋅t) time, where

t is the number of time slots available.

Total Time Complexity: The overall time complexity of the program is dominated by the sorting step, so it is O(nlogn),
where n is the number of jobs.

The time complexity of the program mainly depends on the number of jobs and the number of time slots available.
Sorting the jobs based on profit takes the most significant amount of time, making the overall time complexity
O(nlogn).

PROGRAM CODE:

# Take input from the user for the number of jobs

n = int(input("Enter the number of jobs: "))

# Initialize an empty list to store the jobs

arr = []

# Take input for each job and append it to the list

for i in range(n):

job_name = input(f"Enter the name of job {i + 1}: ")

deadline = int(input(f"Enter the deadline for job {i + 1}: "))

profit = int(input(f"Enter the profit for job {i + 1}: "))

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

arr.append([job_name, deadline, profit])

# Take input for the number of time slots

t = int(input("Enter the number of time slots: "))

# Sort all jobs according to decreasing order of profit

arr.sort(key=lambda x: x[2], reverse=True)

# To keep track of free time slots

result = [False] * t

# To store result (Sequence of jobs)

job = ['-1'] * t

# Iterate through all given jobs

for i in range(len(arr)):

# Find a free slot for this job

# (Note that we start from the last possible slot)

for j in range(min(t - 1, arr[i][1] - 1), -1, -1):

# Free slot found

if result[j] is False:

result[j] = True

job[j] = arr[i][0]

break

# Print the sequence

print("Following is maximum profit sequence of Jobs: ")

print(job)

EXPECTED OUTPUT:

Enter the number of jobs: 5

Enter the name of job 1: a

Enter the deadline for job 1: 2

Enter the profit for job 1: 100

Enter the name of job 2: b

Enter the deadline for job 2: 2

Enter the profit for job 2: 20

Enter the name of job 3: c

Enter the deadline for job 3: 1

Enter the profit for job 3: 40

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

Enter the name of job 4: d

Enter the deadline for job 4: 3

Enter the profit for job 4: 35

Enter the name of job 5: e

Enter the deadline for job 5: 1

Enter the profit for job 5: 25

Enter the number of time slots: 3

Following is maximum profit sequence of Jobs:

['c', 'a', 'd']

EXECUTED OUTPUT:

RESULT: The above Python Program To Find The Job Sequence With Deadline is executed successfully

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

IMPLEMENT THE SUM OF SUBSETS PROBLEM BY USING BACKTRACKING

AIM :

To Implement the Sum Of Subsets Problem By Using Backtracking

DESCRIPTION :

The Sum of Subsets problem involves finding subsets of a set whose sum is equal to a given target
sum. This problem is solved using backtracking, where decisions are made incrementally to include or
exclude elements from the set.

ALOGIRTHM :

• Initialization :

Start with an empty solution subset and begin exploring from the first element of the set.

Maintain a current sum of elements included in the subset.

• Recursive Backtracking Function :

Base Case : If the current subset's sum equals the target sum, print the subset as a solution.

• Recursive Case :

Include the current element in the subset if adding it does not exceed the target sum.

Recursively call the function for the next element.

Backtrack by removing the current element from the subset and explore the option of excluding it.

• Result :

After exploring all possible subsets, the algorithm prints or collects all subsets whose sum equals the
target sum.

TIME COMPLEXITY :

The time complexity of the backtracking algorithm depends on the number of solutions and the
complexity of checking each solution.

In the worst case, all subsets need to be explored, leading to an exponential time complexity O(2N),
where N is the number of elements in the set.

SAPCE COMPLEXITY :

The space complexity is O(N) due to the recursion depth of the backtracking function and the space
required for storing the current subset.

PROGRAM CODE :

def sum_of_subsets(set, subset, n, sum_so_far, target_sum, solutions):

# If sum_so_far equals target_sum, add the current subset to the solutions

if sum_so_far == target_sum:

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

solutions.append(subset[:])

return

# If we've reached the end of the set or exceeded the target sum, return

if n == 0 or sum_so_far > target_sum:

return

# Include the current element in the subset

subset.append(set[n-1])

sum_of_subsets(set, subset, n-1, sum_so_far + set[n-1], target_sum, solutions)

# Exclude the current element from the subset (backtrack)

subset.pop()

sum_of_subsets(set, subset, n-1, sum_so_far, target_sum, solutions)

def read_input():

# Read the set from the user

set = list(map(int, input("Enter the elements of the set (space-separated): ").split()))

# Read the target sum from the user

target_sum = int(input("Enter the target sum: "))

return set, target_sum

def main():

set, target_sum = read_input()

solutions = []

sum_of_subsets(set, [], len(set), 0, target_sum, solutions)

if not solutions:

print("No subsets found.")

else:

print("Subsets found:")

for subset in solutions:

print(subset)

if __name__ == "__main__":

main()

EXPECTED OUTPUT :

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

Enter the elements of the set (space-separated): 1 2 3 4 5

Enter the target sum: 5

Subsets found:

[5]

[4, 1]

[3, 2]

EXECUTED OUTPUT :

RESULT :

The above program to implement sum of subsets problem using backtracking executed successfully.

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

IMPLEMENT THE N-QUEEN’S PROBLEM BY USING BACKTRACKING

AIM :

To Implement the N-QUEEN’S Problem By Using Backtracking

DESCRIPTION :

The N Queens problem involves placing N chess queens on an N×N chessboard so that no two
queens attack each other. This means that no two queens should share the same row, column, or diagonal.

ALOGIRTHM :

• Initialization :

Start with an empty board (N x N chessboard).

Use an array cols where cols[row] represents the column index of the queen placed in row row.

• Recursive Backtracking Function :

Base Case : If all queens are placed successfully (i.e., row == N), print the board configuration.

• Recursive Case :

Iterate through each column (col) for the current row (row).

Check if placing a queen at position (row, col) is safe:

Ensure no other queen shares the same column (col), diagonal (both main diagonal and anti-
diagonal).

If safe, mark (row, col) as part of the solution (cols[row] = col) and recursively call the function for
the next row (row + 1).

Backtrack by undoing the placement if placing a queen does not lead to a solution.

• Result :

After exploring all possible placements, the algorithm prints all distinct solutions (or counts them,
depending on the implementation).

TIME COMPLEXITY :

The time complexity is O(N!)

SPACE COMPLEXITY :

The space complexity is O(N)due to the space required for the cols array to store the column
positions of queens for each row.

PROGRAM CODE :

def is_safe(board, row, col):

# Check this column on the left side

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

for i in range(col):

if board[row][i] == 1:

return False

# Check the upper diagonal on the left side

for i, j in zip(range(row, -1, -1), range(col, -1, -1)):

if board[i][j] == 1:

return False

# Check the lower diagonal on the left side

for i, j in zip(range(row, len(board), 1), range(col, -1, -1)):

if board[i][j] == 1:

return False

return True

def solve_nqueens(board, col):

# If all queens are placed, return True

if col >= len(board):

return True

# Try placing a queen in all rows, one by one

for i in range(len(board)):

if is_safe(board, i, col):

board[i][col] = 1

# Recur to place the rest of the queens

if solve_nqueens(board, col + 1):

return True

# If placing queen in board[i][col] doesn't lead to a solution, remove the queen

board[i][col] = 0

return False

def print_solution(board):

for row in board:

print(" ".join("Q" if x == 1 else "." for x in row))

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

def nqueens():

n = int(input("Enter the number of queens: "))

board = [[0] * n for _ in range(n)]

if not solve_nqueens(board, 0):

print("Solution does not exist")

else:

print_solution(board)

# Run the N-Queens solver

nqueens()

EXPECTED OUTPUT :

Enter the number of queens: 8

Q.......

......Q.

....Q...

.......Q

.Q......

...Q....

.....Q..

..Q.....

EXECUTED OUTPUT :

RESULT :

The above program to implement N-Queen’s problem using BackTracking executed successfully.

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

IMPLEMENT THE GRAPH COLORING BY USING BACKTRACKING

AIM :

To Implement the Graph Coloring By Using Backtracking

DESCRIPTION :

The graph coloring problem involves assigning colors to the vertices of a graph such that no two
adjacent vertices share the same color. The goal is to use the minimum number of colors to color the graph.
This is a common problem in computer science and can be applied in various fields such as scheduling, map
coloring, and register allocation in compilers.

ALGORITHM :

Define a utility function is_safe(graph, v, color, c):

• Check if it is safe to assign color c to vertex v.

• For each adjacent vertex, if it has the same color, return False.

• If no adjacent vertex has the same color, return True.

Define a utility function graph_coloring_util(graph, m, color, v):

• If all vertices are assigned a color (i.e., v == V), return True.

• Try different colors for vertex v.

o For each color, check if it is safe to assign that color using is_safe.

o If it is safe, assign the color and recursively call graph_coloring_util for the next vertex.

o If the recursive call returns True, return True.

o If no color can be assigned, backtrack by removing the color (reset to 0) and try the next
color.

• If no color can be assigned to this vertex, return False.

Define the main function graph_coloring(graph, m):

• Initialize a color array of size V with all values set to 0.

• Call the utility function graph_coloring_util with the initial vertex (0).

• If the utility function returns True, return the color array.

• If it returns False, return "No solution".

Define a function main():

• Take manual input for the number of vertices, the adjacency matrix, and the number of colors.

• Call graph_coloring with these inputs and print the result.

TIME COMPLEXITY :

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

O(m^V), where V is the number of vertices and m is the number of colors.

SPACE COMPLEXITY :

O(V), where V is the number of vertices, due to the recursion stack and the color array.

PROGRAM CODE :

def is_safe(graph, v, color, c):

for i in range(len(graph)):

if graph[v][i] == 1 and color[i] == c:

return False

return True

def graph_coloring_util(graph, m, color, v):

if v == len(graph):

return True

for c in range(1, m + 1):

if is_safe(graph, v, color, c):

color[v] = c

if graph_coloring_util(graph, m, color, v + 1):

return True

color[v] = 0

return False

def graph_coloring(graph, m):

color = [0] * len(graph)

if not graph_coloring_util(graph, m, color, 0):

return "No solution"

return color

# Manual input

def main():

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

print("Enter the number of vertices:")

V = int(input())

graph = []

print("Enter the adjacency matrix:")

for i in range(V):

row = list(map(int, input().split()))

graph.append(row)

print("Enter the number of colors:")

m = int(input())

result = graph_coloring(graph, m)

if result == "No solution":

print(result)

else:

print("Solution exists: Following are the assigned colors")

print(result)

if __name__ == "__main__":

main()

EXPECTED OUTPUT :

Enter the number of vertices:

Enter the adjacency matrix:

0111

1010

1101

1010

Enter the number of colors:

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

Solution exists: Following are the assigned colors

[1, 2, 3, 2]

EXECUTED OUTPUT :

RESULT :

The above program to implement Graph coloring problem using BackTracking executed successfully.

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

IMPLEMENT THE HAMILTONIAN GRAPH BY USING BACKTRACKING

AIM :

To Implement the Hamiltonian Graph By Using Backtracking

DESCRIPTION :

A Hamiltonian graph is a graph that contains a Hamiltonian cycle. A Hamiltonian cycle (or
Hamiltonian circuit) is a cycle that visits each vertex exactly once and returns to the starting vertex.
Determining whether such a cycle exists in a given graph is known as the Hamiltonian Cycle problem, which
is NP-complete.

ALGORITHM :

Start at a vertex. Initialize a path array with the starting vertex.

Recursive utility function. Create a recursive function that takes the current position in the path.

Base Case. If all vertices are included in the path, check if there is an edge from the last included vertex to
the starting vertex.

Try different vertices. For each vertex, check if it can be added to the Hamiltonian Cycle. If so, add the
vertex to the path and call the recursive function.

Backtrack. If adding a vertex does not lead to a solution, remove it from the path and try the next vertex.

Return the path if a Hamiltonian Cycle is found. If the function returns true, the Hamiltonian Cycle is found.

TIME COMPLEXITY :

The time complexity of this algorithm is O(N!), where N is the number of vertices. This is because it
explores all possible permutations of vertices to find the Hamiltonian Cycle.

SPACE COMPLEXITY :

The space complexity is O(N) for the path array plus the space used by the recursion stack, which
also has a maximum depth of O(N). Thus, the overall space complexity is O(N).

PROGRAM CODE :

def is_safe(v, graph, path, pos):

# Check if the current vertex is connected to the previous vertex

if graph[path[pos - 1]][v] == 0:

return False

# Check if the current vertex is already included in the path

if v in path:

return False

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

return True

def hamiltonian_path_util(graph, path, pos):

# Base case: If all vertices are included in the path

if pos == len(graph):

return True

# Try different vertices as the next candidate in the Hamiltonian Path

for v in range(1, len(graph)):

if is_safe(v, graph, path, pos):

path[pos] = v

if hamiltonian_path_util(graph, path, pos + 1):

return True

# Remove the current vertex if it doesn't lead to a solution

path[pos] = -1

return False

def hamiltonian_path(graph):

path = [-1] * len(graph)

# Let the first vertex in the path be 0 (starting point)

path[0] = 0

if not hamiltonian_path_util(graph, path, 1):

print("No Hamiltonian Path found")

return False

print("Hamiltonian Path found:", path)

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

return True

# Example usage with manual input

n = int(input("Enter the number of vertices: "))

graph = []

print("Enter the adjacency matrix:")

for i in range(n):

row = list(map(int, input().split()))

graph.append(row)

hamiltonian_path(graph)

EXPECTED OUTPUT :

Enter the number of vertices: 4

Enter the adjacency matrix:

0110

1011

1101

0110

Hamiltonian Path found: [0, 1, 2, 3]

EXECUTED OUTPUT :

RESULT :

The above program to implement Hamiltonian graph problem using BackTracking executed
successfully.

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

IMPLEMENT THE 0/1 KNAPSACK PROBLEM BY USING BACKTRACKING

AIM :

To Implement the 0/1 Knapsack Problem By Using Backtracking.

DESCRIPTION :

The 0/1 knapsack problem can be solved using backtracking. The goal is to find the maximum total
value of items that can be placed in a knapsack of given capacity, where each item can either be taken or
not (hence 0/1).

ALGORITHM :

• Initialize Inputs :
Read the number of items, their values, weights, and the capacity of the knapsack.
• Base Case : If the number of items is 0 or the capacity is 0, return 0.
• Recursive Case :
If the weight of the current item is more than the remaining capacity, exclude the item and
recursively solve the problem for the remaining items.
Otherwise, solve the problem in two ways :
➢ Include the current item: Add its value to the total and reduce the capacity by its weight.
Recursively solve for the remaining items and updated capacity.
➢ Exclude the current item: Recursively solve for the remaining items without changing the
capacity.
• Return the maximum value obtained from the above two cases.
• Compute and Print Result :
Compute the maximum value that can be obtained and print it.

TIME COMPLEXITY :

The time complexity of the backtracking approach to the 0/1 knapsack problem is 𝑂(2^𝑛), where 𝑛 is
the number of items. This is because for each item, there are two possibilities (include or exclude), leading
to a total of 2𝑛 possible subsets.

SPACE COMPLEXITY :

The space complexity is 𝑂(𝑛), which is the maximum depth of the recursion tree (equal to the
number of items). This space is used by the call stack due to the recursive calls. Each recursive call uses
constant space, and the maximum depth of recursion is 𝑛.

PROGRAM CODE :

def knapsack_backtracking(values, weights, capacity, n):

# Base case: If no items are left or capacity is 0

if n == 0 or capacity == 0:

return 0

# If weight of the nth item is more than knapsack capacity, it cannot be included

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

if weights[n-1] > capacity:

return knapsack_backtracking(values, weights, capacity, n-1)

# Return the maximum of two cases:

# (1) nth item included

# (2) nth item not included

else:

include_item = values[n-1] + knapsack_backtracking(values, weights, capacity - weights[n-1], n-1)

exclude_item = knapsack_backtracking(values, weights, capacity, n-1)

return max(include_item, exclude_item)

# Get user inputs

num_items = int(input("Enter number of items: "))

values = []

weights = []

for i in range(num_items):

value = int(input(f"Enter value of item {i+1}: "))

weight = int(input(f"Enter weight of item {i+1}: "))

values.append(value)

weights.append(weight)

capacity = int(input("Enter capacity of knapsack: "))

# Call the knapsack function

max_value = knapsack_backtracking(values, weights, capacity, num_items)

print(f"The maximum value that can be obtained is: {max_value}")

EXPECTED OUTPUT :

Enter number of items: 4

Enter value of item 1: 2

Enter weight of item 1: 3

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP


Date: Program no: Page no:

Enter value of item 2: 3

Enter weight of item 2: 4

Enter value of item 3: 4

Enter weight of item 3: 5

Enter value of item 4: 5

Enter weight of item 4: 6

Enter capacity of knapsack: 6

The maximum value that can be obtained is: 5

EXECUTED OUTPUT :

RESULT :

The above program to implement 0/1 Knapsack problem using BackTracking executed successfully.

DESIGN AND ANALYSIS OF ALGORITHMS DEPT OF CSE,JNTUACEP

You might also like